Basic HTML version of Foils prepared March 30 97

Foil 28 Control Structures -- foreach Statement (Chapter 4 of the Llama Book)

From PERL4 Tutorial for CPS616 Computational Science for Information Age Course CPS616 -- February 1995. by Geoffrey C. Fox


foreach is similar to statement by this name in C-Shell
foreach $index (@some_list returned by an expression perhaps) {
  • statement-block for each value of $index;
  • }
$index is local to this construct and is returned to any value it had before foreach loop executed
An example that also prints 1 to 10 is
@back= (10,9,8,7,6,5,4,3,2,1);
foreach $num (reverse(@back)) {
  • print $num,"\n";
  • }
In above case one can write more cryptically (a pathological addiction of UNIX programmers)
foreach (sort(@back)) { # sort and reverse give same results here
  • print $_,"\n"; # If an expected variable($num here) 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 Sat Sep 6 1997