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