Perl sorting hash by values in the hash

喜欢而已 提交于 2019-12-31 06:20:31

问题


I think I have the right idea but there's some syntax/convention thing I'm messing up, because I get the error "Global symbol %timeHash requires explicit package name".

Code:

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



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

回答1:


Inline

foreach my $key (sort { $timeHash{$b} <=> $timeHash{$a} } keys %timeHash) {
   print "\t$key\t\t $timeHash{$key}\n";
}

Using a custom sort function the way you are trying to will not work well, because then your sub would need to access the original hash.

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

sub hashValueDescendingNum {
   $timeHash{$b} <=> $timeHash{$a}; # Ew.
}

Instead you can abstract it further:

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;
}

The code is not efficient because it passes around the %hash though, references would be better:

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;
}



回答2:


use List::UtilsBy qw( rev_nsort_by );

foreach my $key ( rev_nsort_by { $timeHash{$_} } keys %timeHash ) {
    ...
}


来源:https://stackoverflow.com/questions/12790891/perl-sorting-hash-by-values-in-the-hash

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!