Perl sorting hash by values in the hash

2019-03-04 07:58发布

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

2条回答
Viruses.
2楼-- · 2019-03-04 08:11

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;
}
查看更多
放荡不羁爱自由
3楼-- · 2019-03-04 08:34
use List::UtilsBy qw( rev_nsort_by );

foreach my $key ( rev_nsort_by { $timeHash{$_} } keys %timeHash ) {
    ...
}
查看更多
登录 后发表回答