我有一个hash(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
答案 0 :(得分:1)
我发现了这个错误。我在脚本的顶部定义了两个变量$a
和$b
并分配了值#34; 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 ...
此错误消息是对错误的暗示。
答案 1 :(得分:0)
您的sort
代码可以正常显示您显示的数据,但cmp
可能应为<=>
将来,请转储参考来汇总变量:
print Dumper \%test