Perl’s control syntax looks like C’s control syntax . Blocks of statements are surrounded by curly braces { }. Statements are terminated with semicolons (;). The parenthesis and curly braces are required in if/while/for forms. There is not a distinct “boolean” type, and there are no “true” or “false” keywords in the language. Instead, the empty string, the empty array, the number 0 and undef all evaluate to false, and everything else is true. The logical operators &&, ||, ! work as in C. There are also keyword equivalents (and, or, not) which are almost the same, but have lower precedence.
IF
if (expr) { ## basic if — ( ) and { } required
stmt;
stmt;
}
if (expr) { ## if + elsif + else
stmt;
stmt;
}
elsif (expr) { ## note the strange spelling of “elsif”
stmt;
stmt;
}
else {
stmt;
stmt;
}
unless (expr) { ## if variant which negates the boolean test
stmt;
stmt;
}
If Variants
As an alternative to the classic if() { } structure, you may use if, while, and unless as modifiers that come after the single statement they control…
$x = 3 if $x > 3; ## equivalent to: if ($x > 3) { $x = 3; }
$x = 3 unless $x <= 3;
For these constructs, the parentheses are not required around the boolean expression. This may be another case where Perl is using a structure from human languages. I never use this syntax because I just cannot get used to seeing the condition after the statement it modifies. If you were defusing a bomb, would you like instructions like this: “Locate the red wire coming out of the control block and cut it. Unless it’s a weekday — in that case cut the black wire.”
Loops
These work just as in C..
while (expr) {
stmt;
stmt;
}
for (init_expr ; test_expr ; increment_expr ) {
stmt;
stmt;
}
## typical for loop to count 0..99
for ($i=0; $i<100; $i++) {
stmt;
stmt;
}
The “next” operator forces the loop to the next iteration. The “last” operator breaks out of the loop like break in C. This is one case where Perl (last) does not use the same keyword name as C (break).
Array Iteration — foreach
The “foreach” construct is a handy way to iterate a variable over all the elements in an array. Because of foreach, you rarely need to write a traditional for or while loop to index into an array.
Foreach is also likely to be implemented efficiently. (It’s a shame Java does not include a compact iteration syntax in the language. It would make Java a better language at the cost of some design elegance.)
foreach $var (@array) {
stmt; ## use $var in here
stmt;
}
Any array expression may be used in the foreach. The array expression is evaluated once before the loop starts. The iterating variable, such as $var, is actually a pointer to each element in the array, so assigning to $var will actually change the elements in the array.