5% assure discount from here only

Showing posts with label sort hash. Show all posts
Showing posts with label sort hash. Show all posts

Tuesday, January 25, 2011

(11) How to sort a hash by value/key?

Solution :

Sorting the output of a Perl hash by the hash key is fairly straightforward. It involves two Perl
functions, keys and sort, along with the good old foreach statement.

(i) sort a hash by key

my %hash = (
"a" => 1,
"c" => 3,
"d" => 4
);

my @keys = sort { $a cmp $b } keys %hash;

foreach my $key ( @keys ){
print $key, $hash{$key};
}

(ii) sort a hash by value

my %hash = (
"a" => 1,
"c" => 5,
"d" => 4
);

my @keys = sort { $hash{$a} <=> $hash{$b} } keys %hash;

foreach my $key ( @keys ){
print $key, $hash{$key};
}