对哈希引用的散列进行排序

问题描述 投票:-2回答:2

我有哈希引用的哈希(test):

use strict;
use warnings 'all';

my %test = (
    110 => { 'foobar' => '3.09' },
    119 => { 'foobar' => '2.08' },
    118 => { 'foobar' => '2.18' },
);

for my $key ( keys %test ) {
    print( "$key, $test{$key}->{'foobar'}\n" );
}

output

110, 3.09
119, 2.08
118, 2.18

但排序是一个问题:

my @sorted = sort { $test{$a}->{'foobar'} cmp $test{$b}->{'foobar'} } keys %test;

Use of uninitialized value in string comparison (cmp) at ...

怎么了?

$ perl -version
This is perl 5, version 24, subversion 1 (v5.24.1) built for i386-openbsd
perl
2个回答
1
投票

我发现了错误。我在脚本的顶部定义了两个变量$a$b,并为它们赋值“0”。在上面的例子中,这导致Perl的sort出现此错误消息。如果使用

my @sorted = sort { $a cmp $b } keys %test;

错误消息变得更加清晰:

"my $a" used in sort comparison at ...
"my $b" used in sort comparison at ...

此错误消息是对错误的暗示。


0
投票

您的sort代码与您显示的数据一起正常工作,除了cmp可能应该是<=>

将来,请转储对聚合变量的引用:

print Dumper \%test
© www.soinside.com 2019 - 2024. All rights reserved.