Logo

Programming-Idioms

History of Idiom 113 > diff from v6 to v7

Edit summary for version 7 by :
[Perl] Alternative impl -> created new impl 1201

Version 6

2016-01-08, 09:58:18

Version 7

2016-01-08, 10:00:19

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";
}

Code
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";
}


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.)
Comments bubble
Create a custom, reusable sort routine and use it by name.
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.