Table of Contents

More Hash Access: Iteration, keys and values

You may have noticed that keys and values return a list. And we can iterate over a list, using foreach :

foreach (keys %countries) {
        print "The key $_ contains $countries{$_}\n";

which is useful. Note how any list can be fed to foreach , and off it goes. As usual, there is another way to do the above:

while (($code,$name)=each %countries) {
        print "The key $code contains $name\n";
The each function returns each key/value pair of the hash, and is slightly faster. In this example we assign them to a list (you spotted the parens ?) and away we go. Eventually there are no more pairs, which returns false to the while loop and it stops.

If you are into brevity, both the above can be accomplished in a single line:

print "The key $code contains $name\n" while ($code,$name)=each %countries;

print "The key $_ contains $countries{$_}\n" foreach keys %countries;

Note -- this won't win any prizes for easily readable code by non-programmers of Perl.