Last modified on 3 September 2014, at 11:49

Perl Programming/Control Flow

Previous: The if Control Structure Index Next: Operators

Control structuresEdit

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

LoopsEdit

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

Though syntactically the same, perl does not use 'break' and 'continue' to change the flow of loops. Perl provides the following commands: (with C equivalents in comments)

while ($boolean) {
    # do something
    if($finished) {
        last;  # equivalent to 'break'
    }
    if($done) {
        next;  # equivalent to 'continue'
    }
    # do some more
}

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, even when specified at the end of the code block. Therefore the following loops are functionally equivalent: (the same applies to: do {} until )

while ($boolean) {
    # something
}
 
do {
    # something
} while ($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.

foreach (@list) {
    print "value: $_ \n";
}

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

If-then statementsEdit

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 AlsoEdit


Previous: The if Control Structure Index Next: Operators