Question: How do I sort a Perl hash by the hash key?
Answer: 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.
This is easiest to demonstrate by example. Suppose we have a class of five students. Their names are kim, al, rocky, chrisy, and jane.
Suppose these students just took a test, and we stored their grades in a hash named grades (note that hashes were called associative arrays prior to the release of Perl 5).
The hash definition might look like this:
%grades = ( kim => 96, al => 63, rocky => 87, chrisy => 96, jane => 79, );
If you're familiar with a Perl hash, you know that the student names are the hash keys, and the test scores are the hash values.
If you want to print out the student names and scores, sorted in alphabetical order by student name, you can use this following Perl code snippet:
print "\n\tGRADES SORTED BY STUDENT NAME:\n";
foreach $key (sort (keys(%grades))) {
print "\t\t$key \t\t$grades{$key}\n";
}
The Perl keys function returns a normal array of the keys of the hash. Our sample hash is named grades, so the keys function returns the names of the students. One attribute of the keys function, however, is that the keys are returned in what appears to be a random order. Therefore, you need to use sort to sort the keys in alphabetical order to get the desired printout.
Here's a complete Perl hash sort example program that prints the contents of the grades hash, sorted by student name:
#!/usr/bin/perl -w
#
# printHashByKey.pl - Created by DevDaily Interactive, Inc.
#
%grades = (
kim => 96,
al => 63,
rocky => 87,
chrisy => 96,
jane => 79,
);
print "\n\tGRADES SORTED BY STUDENT NAME:\n";
foreach $key (sort (keys(%grades))) {
print "\t\t$key \t\t$grades{$key}\n";
}
The output of this program looks like this:
GRADES SORTED BY STUDENT NAME: al 63 chrisy 96 jane 79 kim 96 rocky 87
I hope you found this short Perl hash tutorial helpful. We have many more Perl hash tutorials on this site, including the following:
Getting started Perl hash tutorials:
More advanced Perl hash tutorials:
The hash in Perl - hash sorting tutorials:
Post new comment