Logo

Programming-Idioms

History of Idiom 113 > diff from v7 to v8

Edit summary for version 8 by :
[Perl] Remove last newline

Version 7

2016-01-08, 10:00:19

Version 8

2016-01-08, 10:00:37

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


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
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.
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.