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