Advanced Sorting

Sorting a hash by value

Example

#!/usr/bin/perl


#print clothes sorted by price

%prices = ("shirt"    => 45,
            "pullover" => 90,
            "trousers" => 120,
            "fleece"   => 90,
            "socks"    => 15);
           
@sorted_keys = sort by_value keys (%prices);

foreach $key (@sorted_keys) {
   print "$key: $prices{$key}\n";
}

sub by_value {
   ($prices{$a} <=> $prices{$b}) || ($a cmp $b);
}
Result:
socks: 15
shirt: 45
fleece: 90
pullover: 90
trousers: 120

Table of Contents.
Previous