Sort Perl hash from largest to smallest

18,303

Solution 1

Swap $a and $b:

foreach my $fruit (sort {$data{$b} <=> $data{$a}} keys %data) {

Solution 2

Just use reverse sort instead of sort.

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

Share:
18,303
Ten Digit Grid
Author by

Ten Digit Grid

Updated on June 16, 2022

Comments

  • Ten Digit Grid
    Ten Digit Grid almost 2 years

    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?

  • Mark Reed
    Mark Reed about 12 years
    That works, but sorting and then reversing the list is less efficient than just swapping the sense of the comparison in the first place.
  • toolic
    toolic about 12 years
    @MarkReed: This seems to claim reverse is not less efficient: search.cpan.org/~thaljef/Perl-Critic-1.117/lib/Perl/Critic/…
  • Ωmega
    Ωmega about 12 years
    @MarkReed: reverse is more efficient and more readable code.
  • chepner
    chepner about 12 years
    @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.