Perl hash sort FAQ: 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.
Perl hash sorting - Creating a Perl hash
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.
Perl hash sorting - Printing a Perl hash
If you want to print out the student names and scores, sorted in alphabetical order by student name, you can use this following 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 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 the sort function to sort the keys in alphabetical order to get the desired printout.
A complete Perl hash sort by key program
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 - devdaily.com # %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
Related Perl hash tutorials
I hope you found this short Perl hash tutorial helpful. We have many more Perl hash tutorials on this site, including the following:
Introductory Perl hash tutorials:
- Perl hash introduction/tutorial
- Perl foreach and while: how to loop over the elements in a Perl hash
- Perl hash add - How to add an element to a Perl hash
- How to print each element in a Perl hash
More advanced Perl hash tutorials:
Perl hash sorting tutorials:
- Perl hash sorting - Sort a Perl hash by the hash key
- Perl hash sorting - Sort a Perl hash by the hash value