foreach is similar to statement of same name in C-shell
|
foreach $element (@some_list) {
|
# loop body executes for each value of $element
|
}
|
$element is local to foreach and subsequently returned to the value it had before the loop executed
|
An example that prints the numbers 1 to 10 is
|
@back = (10,9,8,7,6,5,4,3,2,1);
|
foreach $num ( reverse(@back) ) {
|
print $num, "\n";
|
}
|
One can write more cryptically (a pathological addiction of UNIX programmers):
|
foreach (sort(@back)) { # sort(@back) == reverse(@back)
|
print $_, "\n"; # if loop variable is omitted
-
# PERL uses $_ by default
|
}
|