| Developer's Daily | Perl Q&A Center |
| main | java | perl | unix | dev directory | web log |
| Question: | How do I sort a hash by the hash key? |
|
Answer: Sorting the output of a 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 hashes, you know that the student names are the 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 code snippet:
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 sort to sort the keys in alphabetical order to get the desired printout. Here's a test program that prints the contents of the grades hash, sorted by student name:
The output of this program looks like this:
GRADES SORTED BY STUDENT NAME: al 63 chrisy 96 jane 79 kim 96 rocky 87 Thanks for joining us. I hope you enjoyed this article! Three final thoughts before you go:
|
Copyright © 1998 DevDaily Interactive, Inc.
All Rights Reserved.