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) { ...
Author by
Ten Digit Grid
Updated on June 16, 2022Comments
-
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 about 12 yearsThat works, but sorting and then reversing the list is less efficient than just swapping the sense of the comparison in the first place.
-
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 about 12 years@MarkReed:
reverse
is more efficient and more readable code. -
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
.