Logo

Programming-Idioms

History of Idiom 113 > diff from v5 to v6

Edit summary for version 6 by :
New Perl implementation by user [programming-idioms.org]

Version 5

2016-01-07, 20:09:55

Version 6

2016-01-08, 09:58:18

Idiom #113 Iterate over map entries, ordered by values

Print each key k with its value x from an associative array mymap, in ascending order of x.
Note that multiple entries may exist for the same value x.

Idiom #113 Iterate over map entries, ordered by values

Print each key k with its value x from an associative array mymap, in ascending order of x.
Note that multiple entries may exist for the same value x.

Code
for my $k (sort {($mymap{$a}<=>$mymap{$b}) or ($a cmp $b)}
           keys %mymap) {
   print "$k: $mymap{$k}\n";
}
Comments bubble
For a one-off, put the comparison in a code block.
Assuming the keys are strings, we use <=> to compare the numeric values, and cmp to use the lexical order of the key as a tie breaker.