home | O'Reilly's CD bookshelfs | FreeBSD | Linux | Cisco | Cisco Exam    

Book HomeLearning Perl, 3rd EditionSearch this book

3.6. The foreach Control Structure

It's handy to be able to process an entire array or list, so Perl provides a control structure to do just that. The foreach loop steps through a list of values, executing one iteration (time through the loop) for each value:

foreach $rock (qw/ bedrock slate lava /) {
  print "One rock is $rock.\n";  # Prints names of three rocks
}

The control variable ($rock in that example) takes on a new value from the list for each iteration. The first time through the loop, it's "bedrock"; the third time, it's "lava".

The control variable is not a copy of the list element -- it actually is the list element. That is, if you modify the control variable inside the loop, you'll be modifying the element itself, as shown in the following code snippet. This is useful, and supported, but it would surprise you if you weren't expecting it.

@rocks = qw/ bedrock slate lava /;
foreach $rock (@rocks) {
  $rock = "\t$rock";              # put a tab in front of each element of @rocks
  $rock .= "\n";                  # put a newline on the end of each
}
print "The rocks are:\n", @rocks; # Each one is indented, on its own line

What is the value of the control variable after the loop has finished? It's the same as it was before the loop started. The value of the control variable of a foreach loop is automatically saved and restored by Perl. While the loop is running, there's no way to access or alter that saved value. So after the loop is done, the variable has the value it had before the loop, or undef if it hadn't had a value. That means that if you want to name your loop control variable "$rock", you don't have to worry that maybe you've already used that name for another variable.[82]

[82]Unless the variable name has been declared as a lexical in the current scope, in which case you get a lexically local variable instead of a package local variable -- more on this in Chapter 4, "Subroutines".



Library Navigation Links

Copyright © 2002 O'Reilly & Associates. All rights reserved.











??????????????@Mail.ru