Perl sorting hash by values in the hash

后端 未结 2 1430
梦如初夏
梦如初夏 2021-01-28 08:42

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\".

相关标签:
2条回答
  • 2021-01-28 08:56

    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;
    }
    
    0 讨论(0)
  • 2021-01-28 09:05
    use List::UtilsBy qw( rev_nsort_by );
    
    foreach my $key ( rev_nsort_by { $timeHash{$_} } keys %timeHash ) {
        ...
    }
    
    0 讨论(0)
提交回复
热议问题