Sorting a Hash Structure in Perl
How to Sort a Hash structure?
How to sort the hash by keys and by values?
Explanation
Perl uses a the sort() function for sorting an hash. As the hash structure can be seperated by key and values using "$key", $value".
Example :
#! C:programfilesperlbinperl
print "content-type: text/htmlnn";
%name = ('Tom',26,'Peter',51,'Jones', 23, 'John', 43);
print "Sorted by Keys n <br/>";
foreach $key (sort keys %name)
{
print "$key: $name{$key}<br/>";
}
print "Sorted by Values n<br/>";
foreach $value (sort {$name{$a} cmp $name{$b} }keys %name)
{
print "$value: $name{$value}<br/>";
}
Result : Sorted by Keys
John: 43
Jones: 23
Peter: 51
Tom: 26 Sorted by Values
Jones: 23
Tom: 26
John: 43
Peter: 51
In the above example using a loop, first sorting is done based on the keys, then the values are sorted and the elements are displayed.