我有哈希引用的哈希(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" );
}
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
我发现了错误。我在脚本的顶部定义了两个变量$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 ...
此错误消息是对错误的暗示。
您的sort
代码与您显示的数据一起正常工作,除了cmp
可能应该是<=>
将来,请转储对聚合变量的引用:
print Dumper \%test