You'll have noticed that we snuck in something new in the last section -- the if construct. It probably didn't surprise you much - you'll have seen something similar in just about every programming language. (Bonus points will not be given for naming programming languages which have no "if" construct.)
The if construct goes like this:
if (conditional statement) { BLOCK } elsif (conditional statement) { BLOCK } else { BLOCK } |
Both the elsif and else parts of the above are optional, and of course you can have more than one elsif. elsif is also spelt differently to other languages' equivalents - C programmers should take especial note to not use else if.
If you're testing for something negative, it can sometimes make sense to use the similar-but-opposite construct, unless.
unless (conditional statement) { BLOCK } |
There is no such thing as an "elsunless" (thank the gods!), and if you find yourself using an else with unless then you should probably have written it as an if test in the first place.
There's also a shorthand, and more English-like, way to use if and unless:
print "We have apples\n" if $apples; print "Yes, we have no bananas\n" unless $bananas; |
We can repeat a block while a given condition is true:
while (conditional statement) { BLOCK } while ($hunger) { print "Feed me!\n"; $hunger--; } |
The logical opposite of this is the "until" construct:
until ($full) { print "Feed me!\n"; $full++; } |
Perl has a for construct identical to C and Java:
for ($count = 0; $count <= $enough; $count++) { print "Had enough?\n"; } |
However, since we often want to loop through the elements of an array, we have a special "shortcut" looping construct called foreach, which is similar to the construct available in some Unix shells. Compare the following:
# using a for loop for ($i = 0; $i <= $#array; $i++) { print $array[$i] . "\n"; } # using foreach foreach (@array) { print "$_\n"; } |
There are some examples of foreach in exercises/foreach.pl
![]() | foreach(n..m) can be used to automatically generate a list of numbers between n and m. |
We can loop through hashes easily too, using the keys function to return the keys of a hash as an list that we can use:
foreach $key (keys %monthdays) { print "There are $monthdays{$key} days in $key.\n"; } |
We'll look at hash functions later.
Set a variable to a numeric value, then create an if statement as follows:
If the number is less than 3, print "Too small"
If the number is greater than 7, print "Too big"
Otherwise, print "Just right"
Set two variables to your first and last names. Use an if statement to print out whichever of them comes first in the alphabet.
Use a while loop to print out a numbered list of the elements in an array
Now do it with a foreach loop
Now do it with a hash, printing out the keys and values for each item (hint: look up the keys function in your Camel book)
Answers are given in exercises/answers/loops.pl