Perl:使用Data::Dumper时使用内部哈希值对多级哈希进行排序

iqjalb3h  于 2023-11-22  发布在  Perl
关注(0)|答案(1)|浏览(157)

我想使用Data::Dumper打印多级哈希。我想根据内部哈希值对输出进行排序。我尝试了以下几个示例来重新定义Data::Dumper::Sortkeys,以根据键index的值进行排序,但似乎不起作用。下面是我尝试的内容:

use strict;
use Getopt::Long;
use Data::Dumper;
use Storable qw(dclone);
use File::Basename;
use Perl::Tidy;

my $hash = {
    key1 => {
        index => 100,
    },
    key3 => {
        index => 110,
    },
    key2 => {
        index => 99,
    },
    key5 => {
        index => 81,
    },
    key4 => {
        index => 107,
    },

};

#$Data::Dumper::Terse = 1;
$Data::Dumper::Sortkeys =
    sub {
        [sort {$b->{'index'} <=> $a->{'index'}} keys %{$_[0]}];
        };


print Dumper $hash;

字符串
我期望:

$VAR1 = {
    key5 => {
        index => 81,
    },
    key2 => {
        index => 99,
    },
    key1 => {
        index => 100,
    },
    key4 => {
        index => 107,
    },
    key3 => {
        index => 110,
    },

};


这就是我得到的:

$VAR1 = {
          'key5' => {
                      'index' => 81
                    },
          'key4' => {
                      'index' => 107
                    },
          'key3' => {
                      'index' => 110
                    },
          'key2' => {
                      'index' => 99
                    },
          'key1' => {
                      'index' => 100
                    }
        };


我做错了什么?

r8uurelv

r8uurelv1#

变量$a$b保存键,因此必须使用sortkeys子元素中的hashref来访问实际的元素。

use warnings;
use strict;
use Data::Dumper;

my $hash = {
    key1 => {
        index => 100,
    },
    key3 => {
        index => 110,
    },
    key2 => {
        index => 99,
    },
    key5 => {
        index => 81,
    },
    key4 => {
        index => 107,
    },

};

#$Data::Dumper::Terse = 1;
$Data::Dumper::Sortkeys =
    sub {
        my $h = $_[0];
        my @keys =  keys %{$h};
        [ sort {$h->{$a}{index} <=> $h->{$b}{index}} @keys]
        };

print Dumper $hash;

字符串

相关问题