排队
foreach my $key (sort { $timeHash{$b} <=> $timeHash{$a} } keys %timeHash) {
print "\t$key\t\t $timeHash{$key}\n";
}
以您尝试的方式使用自定义排序功能将无法正常工作,因为那样您的子将需要访问原始哈希。
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;
}