Perl hash foreach and while - How to loop over a hash in Perl

Perl hash question: How do I traverse the elements of a hash in Perl?

Answer: There are at least two ways to loop over all the elements in a Perl hash. You can use either (a) a Perl foreach loop, or (b) a Perl while loop with the each function. I find the Perl foreach syntax easier to remember, but the solution with the while loop and the each function is preferred for larger hashes.

A Perl hash/foreach example

Here's some sample Perl code where I show how to loop through all the elements of a hash in Perl, using the Perl foreach operator. I've put a few comments in the code to help explain it:

#!/usr/bin/perl

#---------------------
# create our perl hash
#---------------------

$prices{"pizza"} = 12.00;
$prices{"coke"} = 1.25;
$prices{"sandwich"} = 3.00;

#-------------------------------------
# option 1:
# simple way to traverse a hash.
# fine for when the hash is not large.
#-------------------------------------

print "\nforeach output:\n";
foreach $key (keys %prices)
{
  # do whatever you want with $key and $value here ...
  $value = $prices{$key};
  print "  $key costs $value\n";
}

As you can see, you just use the Perl keys function to get the keys from your hash (%prices), and then loop over the hash with the foreach operator.

Note that you can omit the $value variable in that example, and just use the $prices{$key} reference in the Perl print statement. I just added the extra line to make this Perl hash print example a little more clear.

A Perl hash while/each solution

Here's a very similar example, where I again loop through all the elements of a Perl hash, this time using the each and while operators to traverse the hash:

#!/usr/bin/perl

#---------------------
# create our perl hash
#---------------------

$prices{"pizza"} = 12.00;
$prices{"coke"} = 1.25;
$prices{"sandwich"} = 3.00;

#---------------------------------------------
# option 2:
# traverse the hash using the "each" function.
# better for when the hash may be very large.
#---------------------------------------------

print "\nwhile loop output:\n";
while (($key, $value) = each (%prices))
{
  # do whatever you want with $key and $value here ...
  $value = $prices{$key};
  print "  $key costs $value\n";
}

I haven't tested the speed or memory use of these two approaches, but I have read that this Perl while loop approach is preferred for larger hashes. However, as always, your mileage may vary, and if you're concerned about performance you should test this on your own system and your own Perl hash.

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:

Getting started Perl hash tutorials:

More advanced Perl hash tutorials:

The hash in Perl - hash sorting tutorials: