if (EXPRESSION ) {
STATEMENTS;
}
if (EXPRESSION ) {
# executed if true
STATEMENTS;
} ELSE {
# executed if false
STATEMENTS;
}
if (EXPRESSION ) {
STATEMENTS;
} elsif {
STATEMENTS;
# optional additional ELSIF's
} else {
STATEMENTS;
}
The braces are not optional - requiring braces avoids the dangling else problem.
Perl has no SWITCH statement - it can be imitated several ways, including using ELSIF for each possible case.
while ( EXPRESSION ) {
STATEMENTS;
}
If the condition is initially false,
the body of the loop will never execute.
In the DO-WHILE form, the loop will execute at least once:
do {
STATEMENTS;
} while (EXPRESSION);
for ( INITIAL_EXPR ; COND_EXPR ; LOOP_EXPR ) {
STATEMENTS;
}
The loop is initialized by evaluating INITIAL_EXPR, iterates while
COND_EXPR is true, and evaluates LOOP_EXPR before beginning each subsequent
loop. Example "countdown":
for ( $i=10 ; $i>=0 ; $i-- )
{
print("$i\n");
}
Unlike C, the braces around the block of STATEMETNTS are mandatory
foreach SCALAR ( LIST ) {
STATEMENTS;
}
Each time through the loop, SCALAR is assigned the next element in the LIST,
and the STATEMENTS are executed.
The braces are mandatory.
Example "re-implement a join":
foreach $instrument ("violin","viola","cello","bass")
{
print($instrument," is lighter than a \n");
}
print("harp\n");
Output:
violin is lighter than a viola is lighter than a cello is lighter than a bass is lighter than a harp
# one way to count to 10
$number = 0;
while(1)
{
$number++;
if ($number >= 10 )
{
last;
}
}