Advanced Sorting

Sorting a hash by value

Example

#!/usr/local/bin/perl
use strict;
use warnings;

#print clothes sorted by price

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

my $key;
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.