Skip navigation.
Home
Your source for Perl tips, howto's, faq and tutorials
( categories: )

There are 2 methods:

- Using 'keys' in a 'foreach' loop

foreach my $key ( keys %hash )
{
  print "key: $key, value: $hash{$key}\n";
}

This method has the advantage that it's possible to sort the output by key.

The disadvantage is that it creates a temporary list to hold the keys, in case your hash is very large you end up using lots of memory resources.

- Using 'each' in a 'while' loop

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

This method's advantage is that it uses very little memory (every time 'each' is called it only returns a pair of (key, value) element).

The disadvantage is that you can't order the output by key.