Control Statements

advertisement
Control Statements
Control Expression
• Fundamental part of most control
statements.
• Perl has no boolean type.
• Expression must evaluate to values that can
be interpreted as true or false.
– Return values are strings or numbers.
• 3 kinds of control expressions.
Simple Expression
• Arithmetic or string expressions.
• String expression: If return value is
– String → true.
– “” or “0” → false.
• Arithmetic expression: If return value is
– Number → true.
– 0 → false.
• Undefined values are false.
Relational Expression
• Includes a relational operator.
– e.g. 1 > 2
• Perl has 2 sets of six relational operators.
– One set for numbers.
– One set for strings.
• Produces 1 for true and “” for false
Relational Operators
Operation
Numeric
String
==
eq
Not equal to
!=
ne
Less than
<
lt
Greater than
>
gt
Less than or equal to
<=
le
Greater than or equal
to
>=
ge
Equal to
Compound Expression
• Includes boolean operators.
– ||, &&, !, and, or, not
• Have lower precedence than relational
operators.
• && and || are short circuit ops and return
the last value evaluated.
• Example:
– ($a > 0) && ($b < $limit)
– $a || $b
if Statement
• Syntax:
if (control expression) { … }
elsif (control expression) { …}
else { …}
• Example:
if ($age < 21) {
print “No beer for you! \n”;
}
else {
print “Have another. \n”;
}
while Statement
• Syntax:
while (control expression) {
# loop body
}
• Example:
$sum = 0;
while ($sum <= 1000) {
$sum += <STDIN>;
}
for Statement
• Syntax:
for (initial expr; control expr; increment expr) {
# loop body
}
• All 3 expressions are optional, but (;) is not.
• All 3 expressions can be multiple expressions or
statements.
• Example:
for ($x = 0, $y = 10; $x < 10; $x++, $y--) {
…
}
next, last, and redo
• next, last, and redo can appear in blocks to
provide abnormal flow control.
• next: transfers control to end of block.
• redo: transfers control to top of block.
• last: causes loop to be terminated
immediately
An Example
$count = 0;
while ($name = chomp(<STDIN>) {
if ( length($name) > 5 ) {
next;
}
if ($name eq “Bob”) {
$count++;
}
}
More next, last, and redo
• next, last, and redo can take operands.
• The operand is a loop label.
Loop:
while (…) {
…
next Loop;
…
}
• Effects the labeled loop.
Statement Modifiers
• Single statements can be followed by
modifiers to control execution.
• The modifiers are:
–
–
–
–
–
statement if expression;
statement unless expression;
statement while expression;
statement until expression;
statement foreach expression;
Statement Modifiers (cont.)
• Semantic is straightforward.
• The control expression is evaluated first.
• Example:
– $bob++ if $word eq “bob”;
– $sum *= 2 until $sum > 1000;
Download