Basic HTML version of Foils prepared Sept 20 97

Foil 29 Control Structures -- foreach Statement

From Tutorial on PERL Computational Science for Information Age Course CPS616 -- Sept 20 97. by Geoffrey C. Fox,Nancy McCracken,Tom Scavo


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
}



© Northeast Parallel Architectures Center, Syracuse University, npac@npac.syr.edu

If you have any comments about this server, send e-mail to webmaster@npac.syr.edu.

Page produced by wwwfoil on Sun Sep 21 1997