1.3 Control Flow Constructs
We will now take a rapid trip through all of the Perl control flow constructs. Most of these constructs are taken directly from the C language, although there are some minor differences.
1.3.1 if, else, elsif
An if structure is how decisions are made in Perl. An if has a condition and a code body. If the condition evaluates to non-zero (true), then all the statements in the body of the if are executed. If the condition evaluates to zero (false), then the statements in the body of the if are not executed. The curly braces are required in Perl even when the code body contains only one statement.
if ( $a > $max) { $max = $a; }
The if, else allows for two-way control flow. If the tested condition is true, the code immediately beneath the if is executed; if the tested condition is false, the code beneath the else is executed.
if ( $a > $b) { $max = $a; } else { $max = $b }
Perl also has an elsif construct, which provides a multi-way branch.
print "Enter your grade "; $grade = <STDIN>; if ( $grade < 70 ) # < is the less than operator { print "You get a D\n"; } elsif ( $grade < 80 ) { print "You get a C\n"; } elsif ( $grade < 90) { print "You get a B\n"; } else { print "You get an A\n"; } print "end of construct\n";
Each of these conditions is tested in turn. If one of them is true, then the code body for that condition is executed. The next line to be executed is the line of code beneath the entire construction (print, in this case). The final else is optional and is executed if all the conditions are false.
1.3.2 unless
The unless construct has the exact opposite logic of the if construct; that is, if the tested condition is false, then the code body is executed. unless is not used often except in error checking, as you will see later.
unless ( $a == $b ) # == is the equality operator { print "this stuff executes when\n"; print '$a is not equal to $b\n'; }
1.3.3 while
The while construct is a looping construct. As long as the loop control condition is non-zero, the loop is repeated. When the loop control condition evaluates to false, the loop test fails and the code beyond the while construct is executed. As a side issue here, when Perl encounters a variable that it has not formerly seen, it proceeds as if the value of that variable is zero. Thus, $i does not have to be formally initialized in the loop below:
$i = 0; while ( $i <= 10) # while $i <= 10 { print "$i\n"; $i = $i + 1; } print "code beneath the loop\n";
You can use a while loop to implement an endless loop. Usually, endless loops represent buggy code, but that is not always the case. Here is a common programming idiom:
#!/usr/bin/perl # # length.pl # while ( 1 ) # always true { print "-> "; # issue a prompt $line = <STDIN>; # read a line chomp($line); # nix the newline $len = length($line); # compute line length print "$len is length of $line"; }
The above code waits for the user to enter a line whereupon both the length of the line and the line itself are printed. Then the process is repeated forever. Of course, this type of program needs a way of terminating. Simply type the control-C sequence.
1.3.4 until
The until construct loops until the tested condition is true. When the tested condition becomes true, then the code beyond the until is executed. Most developers prefer while to until because its logic seems to be slightly more straightforward.
$i = 1; until ( $i > 10) { # prints 1 print "$i\n"; # through 10 $i = $i + 1; # }
1.3.5 for
A for loop is yet another way of looping. This construct has two parts: the for statement and the code body. The for statement itself has three parts separated by semicolons: the initialization, the test, and the modification. First, the initialization takes place. Next, the condition is tested. If the condition is true, then the code body is executed, after which the modification step is executed. The loop continues with a retesting of the condition, etc.
for ( $i = 1; $i <= 10; $i = $i + 1) { $s = $s + $i; # compute sum of } # first 10 integers
1.3.6 foreach
The foreach loop is similar to a for loop except that the number of iterations of this style of loop is determined by a set of list elements in the foreach statement. Here is a foreach loop that totals the elements in an array:
@list = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10); foreach $item (@list) { $sum = $sum + $item; }
Each item in the @list array is bound to the loop variable, $item in this code, which in turn is added to $sum. It is important to know that inside a foreach loop, the control variable is an alias for the element in the list to which it is currently bound. Because of this, a change to the control variable is, in effect, a change to the list element. We can use this concept to change each array element.
foreach $ref (@list) { $ref = $ref * 2; # double each item }
Each iteration above doubles the element to which $ref is bound. Thus, at the end of the loop, all of the elements in the @list array have been doubled.
1.3.7 Statement modifiers
Unlike other languages, Perl always requires the open and close curly braces when your code uses the keywords unless, until, while, if, for, and foreach. This is true even if your control flow construct only has one statement in it. Thus, each of the following generates an error in translation:
if ( $a > $b ) # error: no curly braces print "$a > $b\n"; unless ($a > $b) # error: no curly braces print "$a <= $b\n";
However, for those cases in which there is only one statement inside the control structure, Perl allows a shorter form called the modifier form. This form may be used with if, unless, while, and until. To use this form, simply code one statement before the control structure.
$x = 50; $y = 10; $name = "Mike"; print "$name\n" if $x > $y; print "$name\n" unless $x < $y; print "$name\n" while $y++ < $x; # ++ to be explained later print "$name\n" until $x > $y++; # ++ to be explained later
Keep in mind the control structure is still evaluated first, so any statement execution still depends on the truth of the test. When you use this form, the set of parentheses that delimits the condition is not required.
1.3.8 What is true and what is false?
In many of the control structures above, a test must be made to determine if the body of the control structure is executed. When an expression is tested for true or false, Perl only cares about whether the expression has the value zero or not. Zero is considered false and anything else is considered true. There are different versions of zero, however! Each of the following is considered to be zero: "", "0", 0, and 0.0.