Presenting Mathematical Concepts on the World Wide Web
Forms & Scripts

Perl: Program Control

You know what's coming; there has to be a loop, and if-then, and ...

Loops

On account of its wildly polymorphic nature, virtually any kind of loop construct you can think of works in Perl. Here are a few.
# Standard for loop

for ($i=0; $i < 10; $i++) {
   print "$i \n";
}

$x[0] = "Manet";    $x[1] = "Cezanne";
$x[2]="Kandinsky";  $x[3] = "Pollack";

# foreach loop

foreach $name (@x) {     # note parentheses
  print "$name \n";
}

# do loop

$j = 5;
do {
  print "$j \n";
  $j += .2;
}
until ($j > 6.1);

# mutant hybrid Perl thing

until ($j > 7) {
  print "$j \n";
  $j += .2;
}

Conditionals

Same story here. Perl hackers are especially fond of "short circuit" conditionals.
$a = 1; $b = 2;

# standard if -- the braces are *not* optional

if ($a > $b) {
  print "goats ";
}

# if at the end

print "hounds " if ($b > $a);

# short circuit conditional

($a > $b) || print "oxen ";

# something other than 'if' for variety

print "flamingos " unless ($a > $b);

C hackers' delight

($a > $b) ? print "humuhumunukunukuapuaa " : print "ginko ";

print "\n";


Next: Pattern Matching
Back: Variables
Up: Forms & Scripts


Presenting Mathematical Concepts on the World Wide Web. Copyright © 1997 by Carol Scheftic. All rights reserved. (This section was originally copyrighted in 1996 by The Geometry Center and is re-used here with permission.) Please send comments on this page, or requests for permission to re-use material from this page, to: scheftic@geom.umn.edu
Page established 1-Jun-97; last updated Thursday, 24-Jul-1997 01:20:53 CDT.