Perl

  1. Home
  2. Computing & Technology
  3. Perl

Perl each() function - Quick Tutorial

How to use the each() function

From About.com

each HASH
Perl's each() function is used to iterate (loop) through the the key / value pairs of a HASH. Each key / value pair is returned as a two-element list.
%contact = ('name' => 'Bob', 'phone' => '111-111-1111');
while (($key, $value) = each %contact) {
print "$key=$value\n";
}
In the above example, we start with a simple hash of our contact Bob and his phone number. The each function takes this regular hash as input, and is couched in a while loop. Here is the each function standing on it's own:
($key, $value) = each %contact
Every time the each function is called, it grabs an element out of the hash and puts them in the $key and $value strings. When couched in the while statement it will loop through each element of the hash and pass them off to the print statement.
There are a couple of things to keep in mind when using the each function. Because of the way Perl works with hashes, the elements will be returned in random order. Also, the each function does not remove the elements from the hash - the hash is unaffected by the looping process.
More Perl Quick Tips

Explore Perl

More from About.com

Perl

  1. Home
  2. Computing & Technology
  3. Perl
  4. Programming Perl
  5. Perl each function reference - learn how to use Perl's each() function in this quick tutorial.

©2009 About.com, a part of The New York Times Company.

All rights reserved.