Logo

Programming-Idioms

History of Idiom 113 > diff from v4 to v5

Edit summary for version 5 by :
New Perl implementation by user [Roboticus]

Version 4

2016-01-05, 09:50:34

Version 5

2016-01-07, 20:09:55

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
# Normally, you'll use the same sort scheme in multiple places,
# so you can create a custom sort routine and use it by name
sub by_val_then_key {
    return ($mymap{$a} <=> $mymap{$b})
        or ($a cmp $b)
}

for my $k (sort by_val_then_key keys %mymap) {
   print "$k: $mymap{$k}\n";
}

# For a one-off, just put the comparison in a code block
for my $k (sort {($mymap{$a}<=>$mymap{$b}) or ($a cmp $b)}
           keys %mymap) {
   print "$k: $mymap{$k}\n";
}

Comments bubble
I'm assuming the keys are strings, so we use <=> to compare the numeric values, and cmp to use the lexical order of the key as a tie breaker.)