Next: Pattern Matching
Up: CGI Scripts with Perl
Prev: Variables

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
Up: CGI Scripts with Perl
Prev: Variables

[HOME] The Geometry Center Home Page

Comments to: webmaster@geom.umn.edu
Created: May 07 1996 --- Last modified: May 29 1996