| Developer's Daily | Perl Q&A Center |
| main | java | perl | unix | dev directory | web log |
| Question: | How do I do <fill-in-the-blank> for each element in a hash? |
|
Answer: Software developers are always working with arrays. In Perl, that means that you're working with either (a) normal arrays or (b) hashes. (Note: hashes were called 'associative arrays' before Perl 5.x). Here's a simple technique we use to process each element in a hash:
In this example, %days is a small hash that associates short day names ('Sun', 'Mon', etc.) with their corresponding full names ('Sunday', 'Monday', etc.). Within the foreach loop, the short day name is represented by the symbol $key, and the long name is retrieved from the hash with the $days{$key} syntax. The output of this program looks like this: The long name for Fri is Friday. The long name for Mon is Monday. The long name for Sat is Saturday. The long name for Sun is Sunday. The long name for Thu is Thursday. The long name for Tue is Tuesday. The long name for Wed is Wednesday. You can see that the output is sorted alphabetically by the short day name. Note that it is not necessary to use the sort function in the foreach loop. Whether you need to use the sort function depends on what you're trying to accomplish. We could have also written the program without the sort function, like this:
In this case, our unsorted output looks like this: The long name for Sat is Saturday. The long name for Wed is Wednesday. The long name for Fri is Friday. The long name for Thu is Thursday. The long name for Mon is Monday. The long name for Tue is Tuesday. The long name for Sun is Sunday. You can clearly see in this example that the keys function returns the hash keys in what appears to be a random order. This is the primary reason that sort is often used when processing hashes. If you're interested in using this technique
when tackling your hashes, all you have is put
your logic inside one of the Final notes If you're interested in working with hashes, you may be interested in the following articles related to hashes:
Good luck, and happy coding! |
Copyright © 1998 DevDaily Interactive, Inc.
All Rights Reserved.