A Perl hash print example (printing hash elements)

Perl hash question: How do I print the elements stored in a hash in Perl?

Answer: There are at least two ways to print the elements of a Perl hash, including one way that I think is easy to remember, and another way that is recommended if you have a very large hash.

Perl hash printing with a foreach loop

The easier way for me to remember is with a Perl foreach loop. In the following sample code I'll first create a Perl hash, and then I'll print out each key and value stored in the hash:

#!/usr/bin/perl

# create our perl hash
$prices{"pizza"} = 12.00;
$prices{"coke"} = 1.25;
$prices{"sandwich"} = 3.00;

#--------------------------------------------------
# option 1:
# print the hash key and value using a foreach loop
#--------------------------------------------------
foreach $key (keys %prices)
{
  print "$key costs $prices{$key}\n";
}

As mentioned, I think this Perl foreach syntax is easier to remember, and I use it very often.

The Perl while/each approach

The second approach is to the use Perl's each operator and a Perl while loop. Here's a sample Perl script that demonstrates this:

#!/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.
#---------------------------------------------

while (($key, $value) = each (%prices))
{
  print "$key costs $prices{$key}\n";
}

As mentioned, I can't seem to remember this Perl while/each syntax as easily as I can remember the Perl foreach syntax, but this approach is supposed to perform better than the other approach. I haven't tested this performance myself, so if you think you have a very large hash in Perl script, and performance is slow, you can try this as an optimization approach.

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:

Share it!

There’s just one person behind this website; if this article was helpful (or interesting), I’d appreciate it if you’d share it. Thanks, Al.

Add new comment

The content of this field is kept private and will not be shown publicly.

Anonymous format

  • Allowed HTML tags: <em> <strong> <cite> <code> <ul type> <ol start type> <li> <pre>
  • Lines and paragraphs break automatically.
By submitting this form, you accept the Mollom privacy policy.