1

我认为我的想法是正确的,但是我搞砸了一些语法/约定,因为我收到错误“全局符号 %timeHash 需要显式包名称”。

代码:

foreach $key (sort hashValueDescendingNum (keys(%timeHash))) {
   print "\t$key\t\t $timeHash{$key}\n";
}



sub hashValueDescendingNum {
   my $hash = shift;
   $hash{$b} <=> $hash{$a};
}
4

2 回答 2

3

排队

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;
}
于 2012-10-08T23:33:16.137 回答
0
use List::UtilsBy qw( rev_nsort_by );

foreach my $key ( rev_nsort_by { $timeHash{$_} } keys %timeHash ) {
    ...
}
于 2012-10-10T10:26:27.037 回答