Sort Perl hash from largest to smallest

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

And it gives this code to sort the hash based on each key value:

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

I don’t quite understand this code, but when I experiment with it, it is sorted from lowest to highest. How can I flip it to sort from highest to lowest?

+3
source share
2 answers

Change $aand $b:

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

Just use reverse sortinstead sort.

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

+14
source

All Articles