4.6 The foreach StatementYet another iteration construct is the foreach The original value of the scalar variable is automatically restored when the loop exits; another way to say this is that the scalar variable is local to the loop. Here's an example of a @a = (1,2,3,4,5);
foreach $b (reverse @a) {
print $b;
}This program snippet prints You can omit the name of the scalar variable, in which case Perl pretends you have specified the
@a = (1,2,3,4,5);
foreach (reverse @a) {
print;
}See how using the implied If the list you are iterating over is made of real variables rather than some function returning a list value, then the variable being used for iteration is in fact an alias for each variable in the list instead of being merely a copy of the values. Consequently, if you change the scalar variable, you are also changing that particular element in the list that the variable is standing in for. For example: @a = (3,5,7,9);
foreach $one (@a) {
$one *= 3;
$x = 17;
@a = (3,5,7,9);
@b = (10,20,30);
foreach $one (@a, @b, $x) {
$one *= 3;
}
# $x is now 51
# @a is now (9,15,21,27)
# @b is now (30,60,90);
}
# @a is now (9,15,21,27)Notice how altering |