O'Reilly logo

Perl Cookbook by Nathan Torkington, Tom Christiansen

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Traversing a Hash

Problem

You want to perform an action on each entry (i.e., each key-value pair) in a hash.

Solution

Use each with a while loop:

while(($key, $value) = each(%HASH)) {
    # do something with $key and $value
}

Or use keys with a foreach loop, unless the hash is potentially very large:

foreach $key (keys %HASH) {
    $value = $HASH{$key};
    # do something with $key and $value
}

Discussion

Here’s a simple example, iterating through the %food_color hash from the introduction.

# %food_color per the introduction
while(($food, $color) = each(%food_color)) {
    print "$food is $color.\n";
}

                  Banana is yellow.
               
                  Apple is red.
               
                  Carrot is orange.
               
                  Lemon is yellow.

foreach $food (keys %food_color) {
    my $color = $food_color{$food};
    print "$food is $color.\n";
}

                  Banana is yellow.
               
                  Apple is red.
               
                  Carrot is orange.
               
                  Lemon is yellow.

We didn’t really need the $color variable in the foreach example because we only use it once. Instead, we could have just written:

print "$food is $food_color{$food}.\n"

Every time each is called on the same hash, it returns the “next” key-value pair. We say “next” because the pairs are returned in the order the underlying lookup structure imposes on them, and this order is almost never alphabetic or numeric. When each runs out of hash elements, it returns the empty list (), which tests false and terminates the while loop.

The foreach example uses keys, which constructs an entire list containing every key from hash, before the loop even begins executing. The advantage to using ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required