Perl Programming/Control Flow

From Wikibooks, open books for an open world
Jump to: navigation, search
Previous: The if Control Structure Index Next: Operators

Control structures[edit]

The basic control structures do not differ greatly from those used in the C programming language or Java programming language:

Loops[edit]

while ($boolean) {
    # do something
}
 
until ($boolean) {
    # do something
}

Note that the statements in a while (or until) loop are not executed if the Boolean expression evaluates to false (or true, respectively) on the first pass.

do {
    # something
} while ($boolean);
 
do {
    # something
} until ($boolean);

The do {} while and the do {} until loops are technically statement modifiers and not actual control structures. The statements will be executed at least once.

for (my $i=0 ; $i<10 ; $i++) { # for (initialization; termination condition; incrementing expr) { ... }
    print "$i\n";
}
 
foreach my $variable (@list) {
    print "$variable\n";
}

$variable is an alias to each element of the @list, starting at the first element on the first pass through the loop. The loop is exited when all the elements in the list have been exhausted. Since $variable is an alias, changing the value will change the value of the element in the list. This should generally be avoided to enhance maintainability of the code.

If $variable is omitted, the default variable $_ will be used.

Note that for and foreach are actually synonyms and can be used interchangeably.

If-then statements[edit]

if ($boolean_expression) {
    # do something
}
 
unless ($boolean_expression) {
    # do something
}

Statements with else blocks (these also work with unless instead of if)

if ($boolean) {
    # do something
}
else {
    # do something else
}
 
if ($boolean) {
    # do something
}
elsif ($boolean) {
    # do something else
}

Control statements can also be written with the conditional following the statements (called "postfix"). This syntax functions (nearly) identically to the ones given above.

statement if Boolean expression;
statement unless Boolean expression;
statement while Boolean expression;
statement until Boolean expression;
statement foreach list;

See Also[edit]


Previous: The if Control Structure Index Next: Operators