Perl Programming/Control flow

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

Loops
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)

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)

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.

$variable is an alias to each element of the <tt>@list</tt>, 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 <tt>$variable</tt> 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 <tt>$variable</tt> is omitted, the default variable <tt>$_</tt> will be used.

Note that <tt>for</tt> and <tt>foreach</tt> are actually synonyms and can be used interchangeably.

Blocks may have an optional <tt>continue</tt> section, which is executed at the end of each iteration.

<tt>next</tt>, <tt>redo</tt>, <tt>last</tt>
When inside a loop, there are three keywords that manipulate how the loop is handled.

To start the next iteration, <tt>next</tt> jumps to the end of the block. If there is a <tt>continue</tt> block, that part is executed, as is the conditional to resume the loop.

To restart an iteration, <tt>redo</tt> jumps to the beginning of the block. Neither <tt>continue</tt> nor the conditional are executed.

To break out of the loop, <tt>last</tt> jumps outside the end of the block. Neither <tt>continue</tt> nor the conditional are executed.

<tt>given</tt>
Until version 5.10.1, Perl did not have an equivalent of the switch statement in other programming languages. Starting in that version, it became an experimental feature.

In Perl 5, it first needs to be enabled with one of the following statements:

By default, the expressions in <tt>when</tt> is matched to what is found in <tt>given</tt>. In certain exceptional cases, the value may be used directly as a boolean.

<tt>if-then</tt> statements
Statements with <tt>else</tt> blocks (these also work with <tt>unless</tt> instead of <tt>if</tt>)

Postfix notation
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;