How do I do (fill in the blank) for each element in a Perl hash?

Question: How do I do (fill in the blank) for each element in a Perl 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).

Sample program: Process each element in a hash

Here's a simple technique we use to process each element in a hash:

#!/usr/bin/perl -w

%days = (
        'Sun' => 'Sunday',
        'Mon' => 'Monday',
        'Tue' => 'Tuesday',
        'Wed' => 'Wednesday',
        'Thu' => 'Thursday',
        'Fri' => 'Friday',
        'Sat' => 'Saturday' );

foreach $key (sort keys %days) {
  print "The long name for $key is $days{$key}.\n";
}

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.

Program output

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.

Unsorted output

We could have also written the program without the sort function, like this:

#!/usr/bin/perl -w

%days = (
        'Sun' => 'Sunday',
        'Mon' => 'Monday',
        'Tue' => 'Tuesday',
        'Wed' => 'Wednesday',
        'Thu' => 'Thursday',
        'Fri' => 'Friday',
        'Sat' => 'Saturday' );

# foreach loop w/o 'sort' function
foreach $key (keys %days) {
  print "The long name for $key is $days{$key}.\n";
}

Unsorted output

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 foreach loops shown above.

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!

What's Related


devdaily logo