Loops
- Braces are required
While loop
while (expr) {
statements;
}
while (expr) {
statements;
} continue {
statements;
}
- If there's a
continueblock, it's always executed just before the conditional expression.
single-statement while (expr);
Until loop
- Logical negation of a
whilestatement: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
forcan be used in place offoreach - 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 (likebreakin C / C++)next: Continue on to the next iteration of the loop (likecontinuein C / C++)redo: Restart the current iteration of the loop block, without executing thecontinueblock 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
Resources URL:
notes/perl/resources
Sources URL:
notes/perl/sources