Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort Perl hash from largest to smallest

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?

like image 438
Ten Digit Grid Avatar asked Nov 28 '22 17:11

Ten Digit Grid


2 Answers

Just use reverse sort instead of sort.

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

like image 61
Ωmega Avatar answered Dec 10 '22 02:12

Ωmega


Swap $a and $b:

foreach my $fruit (sort {$data{$b} <=> $data{$a}} keys %data) {
like image 34
chepner Avatar answered Dec 10 '22 02:12

chepner