Question

I am trying to use this code, but it attempts to sort the keys instead, which it cannot do because they are not numerical.

foreach my $word (sort {$b <=> $a} keys %wordHash) {
        printf ("%-20s %10d\n", $word, $wordHash{$word});
}
Was it helpful?

Solution

  • If you want to print your hash in the values order, then you simply need to compare values in your sort block instead of comparing the keys themselves:

     { $wordHash{$b} <=> $wordHash{$a} } 
     # The rest of your code stands
    

    This works because the block used in sort can be ANY anonymous subroutine with arbitrary logic; as long as it returns positive/0/negative values.

  • If you only want sorted values irrespective of keys, even simpler (seems kinda pointless so I assume you wanted the previous option, but just in case I'll answer this as well):

     sort {$b <=> $a} values %wordHash
    
  • Also, if you want to print in keys order but sorted alphabetically instead of numerically, default sort sorts lexically (same as { $a cmp $b }):

     sort keys %wordHash               # sort in ascending alphanumeric
     reverse sort keys %wordHash       # sort in descending alphanumeric
     sort { $b cmp $a } keys %wordHash # same: descending alphanumeric,
                                       #   faster on large data but less readable
    
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top