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};
}
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};
}
SORTING THE HASH BY KEY
ReplyDelete@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";
}
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