if
all by itself, in lines likeprint "You're 28!\n" if ($age == 28);That's really shorthand for
if ($age == 28) { print "You're 28!\n"; }which means, "if $age equals 28, then do everything inside the curly brackets." The if/then control structure can be extended with
elsif
and else
:if ($age == 28) { print "You're 28!\n"; } elsif ($sex eq "f") { print "You're a female!\n"; } elsif ($sex eq "m") { print "You're a male!\n"; } else { print "You're a mystery to me..."; }Only the first true statement will match. So if ($age == 28) and ($sex eq "f"), you'll get the output
You're 28!
else
is the default; its commands will be executed only
if none of the preceding statements in the control structure were
true.
for
loop. For instance, to print the numbers 1
through 10:#!/usr/bin/perl for($x=1; $x<=10; $x++) { print "$x\n"; }The three parts inside the for() translate as: a) set the counter, $x, to equal one; b) check to see if $x is less than or equal to ten, and if it is, execute all the commands inside the curly brackets; c) once you've executed the commands inside the curly brackets, add 1 to $x ($x++ means "add one to x") and then go back to b).
There's fancier things you can do with a for loop, but we'll leave it at that for now. Suffice it to say that the three statements inside the parens take the form:
if
, and you can use it just
like if:print "Dog isn't cat!\n" unless ($dog eq $cat);or
unless ($dog eq $cat) { block of commands ... }
until($x == "15"){ print "You have to type in 15!\n"; $x = &getnumber; }
$seven = 7; (@array) = (1,5,$seven,"catapult"); foreach $element (@array) { print "$element\n"; }So, for instance, if your array "@movies" was loaded up with the names of the 6000 movies in your collection of videotapes, you could
foreach $title (@movies){ print "$title\n" if ($title =~ /Tonight/); }to find out how many of your movies have the word "Tonight" in the title.
Fun stuff like that can keep a Perl programmer up all night, I guarantee. Zzzzz!