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


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 }

in Table To:


© 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