Loops

  • Braces are required

While loop

while (expr) {
statements;
}
while (expr) {
statements;
} continue {
statements;
}
  • If there's a continue block, it's always executed just before the conditional expression.
single-statement while (expr);

Until loop

  • Logical negation of a while statement: while (!expr)
until (expr) {
statements;
}
single-statement until (expr);

Do ... while

do {
statements;
} while (expr);

For loop

for (initial-expr; cond-expr; incr-expr) {
statements;
}

Foreach loop

foreach my $str ("one", "two", "three") {
print $str;
}
foreach (@array1) {
print $_;
}
foreach (1..15) {
...
}
foreach (1..15, 30..35) {
...
}
# Loops for each even number from 2 to 200
foreach (map { $_ *= 2 } 1..100) {
...
}
foreach my $scalar1 (@array1) {
...
} continue {
...
}
# Print the %ENV hash
foreach my $key (keys %ENV) {
print "$key = $ENV{$key}\n";
}
  • The keyword for can be used in place of foreach
  • Each element of the list is stored in the named variable; if no variable is named, the default variable $_ is used
  • The named variable in the loop is either explicitly local, if it's preceded by my, or it's implicitly local, in which case the variable regains its former value after exiting the loop
  • The named variable contains a copy of the current element in the list; modifying the variable does not modify the element in the list (?)
  • The named variable is an implicit alias for each item in the list

Jump statements

  • last  : Break from the loop (like break in C / C++)
  • next  : Continue on to the next iteration of the loop (like continue in C / C++)
  • redo  : Restart the current iteration of the loop block, without executing the continue block or evaluating the conditional
LINE: while (<STDIN>) {
next LINE if /^#/; # Discard comments
last LINE if /^$/; # Exit when find an empty line
if (s/$//) { # If the input line ends in a backslash
$_ .= <>;
redo LINE unless eof();
}
...
}
  • In the above example, an input line that ends in a backslash indicates continuation, input that spans multiple lines, in which case the current iteration of the loop continues on with the next input line

Labels

  • Consists of an identifier followed by a colon
  • Used to identify the loop that the loop control statements refer to
  • If the label is omitted, the loop control statements refer to the innermost enclosing loop
LABEL while (expr) BLOCK
LABEL for (expr; expr; expr) BLOCK
LABEL foreach VAR (LIST) BLOCK