Monday, April 03, 2006

Perl : Sorting a hash

Consider this hash.
%my_hash = ("apple"=>20,"banana"=>5,"chiku"=>10,"pineapple"=>30,"mango"=>50);

Keys of this hash are names of fruit and the values are numbers.
With 'sort' and 'keys' functions we get a hash sorted by its keys.

foreach $k(sort keys %my_hash){
        print "$k => $my_hash{$k}\n";
}

This prints
----------------------
apple => 20
banana => 5
chiku => 10
mango => 50
pineapple => 30
----------------------

Following code reverse-sorts the same hash by its values and prints it.

foreach $k(sort { $my_hash{$b} <=> $my_hash{$a} } keys %my_hash){
        print "$k => $my_hash{$k}\n";
}

Output
---------------------
mango => 50
pineapple => 30
apple => 20
chiku => 10
banana => 5
---------------------

The above can be done with this code.

foreach $k(reverse sort { $my_hash{$a} <=> $my_hash{$b} } keys %my_hash){
        print "$k => $my_hash{$k}\n";
}

Notes :
  • 'reverse' has been added in the above code so that sorting takes place in revese way. However, the positions of $a and $b have changed too.
  • <=> is used for numerical comparison. This is the comparison operator.
  • 'cmp' is used for comparison of strings.
  • The operators '<=>' and 'cmp' return either of 1,0,-1. These when used with 'sort' do the sorting !

No comments: