我认为我有正确的想法,但有一些语法/惯例我搞砸了,因为我收到错误“全局符号%timeHash需要显式包名称。”
代码:
foreach $key (sort hashValueDescendingNum (keys(%timeHash))) {
print "\t$key\t\t $timeHash{$key}\n";
}
sub hashValueDescendingNum {
my $hash = shift;
$hash{$b} <=> $hash{$a};
}
答案 0 :(得分:2)
内联
foreach my $key (sort { $timeHash{$b} <=> $timeHash{$a} } keys %timeHash) {
print "\t$key\t\t $timeHash{$key}\n";
}
使用自定义排序功能,您尝试的方式将无法正常工作,因为您的sub需要访问原始哈希。
foreach my $key (sort hashValueDescendingNum (keys(%timeHash))) {
print "\t$key\t\t $timeHash{$key}\n";
}
sub hashValueDescendingNum {
$timeHash{$b} <=> $timeHash{$a}; # Ew.
}
相反,你可以进一步抽象它:
foreach my $key (sortedHashKeysByValueDescending(%timeHash)) {
print "\t$key\t\t $timeHash{$key}\n";
}
sub sortedHashKeysByValueDescending {
my %hash = @_;
my @keys = sort { $hash{$b} <=> $hash{$a} } keys %hash;
return @keys;
}
代码效率不高,因为它传递%hash,但引用会更好:
foreach my $key (sortedHashKeysByValueDescending(\%timeHash)) {
print "\t$key\t\t $timeHash{$key}\n";
}
sub sortedHashKeysByValueDescending {
my $hash = shift;
return sort { $hash->{$b} <=> $hash->{$a} } keys %$hash;
}
答案 1 :(得分:0)
use List::UtilsBy qw( rev_nsort_by );
foreach my $key ( rev_nsort_by { $timeHash{$_} } keys %timeHash ) {
...
}