4

I am looking at an example found here: http://perlmeme.org/tutorials/sort_function.html

And it gives this code to sort a hash based on each key's value:

# Using <=> instead of cmp because of the numbers
    foreach my $fruit (sort {$data{$a} <=> $data{$b}} keys %data) {
        print $fruit . ": " . $data{$fruit} . "\n";
    }

This code I do not fully understand, but when I experiment with it, it sorts from lowest to highest. How can I flip it to sort from highest to lowest?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Ten Digit Grid
  • 1,315
  • 4
  • 22
  • 43

2 Answers2

16

Just use reverse sort instead of sort.

foreach my $fruit (reverse sort keys %data) { ...

Ωmega
  • 42,614
  • 34
  • 134
  • 203
  • 2
    That works, but sorting and then reversing the list is less efficient than just swapping the sense of the comparison in the first place. – Mark Reed Apr 18 '12 at 19:25
  • 6
    @MarkReed: This seems to claim `reverse` is not less efficient: http://search.cpan.org/~thaljef/Perl-Critic-1.117/lib/Perl/Critic/Policy/BuiltinFunctions/ProhibitReverseSortBlock.pm – toolic Apr 18 '12 at 19:45
  • @MarkReed: `reverse` is more efficient and more readable code. – Ωmega Apr 18 '12 at 20:09
  • 1
    @toolic: Interesting, did not know that. I wonder if the optimization extends to comparing `$data{$a}` and `$data{$b}`, instead of just `$a` and `$b`. – chepner Apr 19 '12 at 13:30
14

Swap $a and $b:

foreach my $fruit (sort {$data{$b} <=> $data{$a}} keys %data) {
chepner
  • 497,756
  • 71
  • 530
  • 681