5% assure discount from here only

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

2 comments:

  1. SORTING THE HASH BY KEY

    @sort_key=sort(keys %where); #sorting the key values and storing in an array
    print "sorting by key",@sort_key,"\n";

    foreach $key(@sort_key) #finding for every sorted key value corresponding value
    {
    print $key,"\t",$where{$key},"\n";
    }

    ReplyDelete
  2. We have written in full detail on sorting the hash and array elements with lots of examples here: http://www.aliencoders.org/content/sorting-array-and-hash-elements-perl/

    ReplyDelete