Perl supports many kinds of loop constructs: for/foreach, while/do-while, and until.
@numbers = 1..42;
for (my $i=0; $i <= $#numbers; $i++) {
print "$numbers[$i]\n";
}
#Can also be written as
foreach my $num (@numbers) {
print "$num\n";
}
The while loop evaluates the conditional before executing the associated block. So, sometimes the block is never executed. For example, the following code would never be executed if the filehandle $fh
was the filehandle for an empty file, or if was already exhausted before the conditional.
while (my $line = readline $fh) {
say $line;
}
The do
/while
and do
/until
loops, on the other hand, evaluate the conditional after each time the block is executed. So, a do
/while
or a do
/until
loop is always executed at least once.
my $greeting_count = 0;
do {
say "Hello";
$greeting_count++;
} until ( $greeting_count > 1)
# Hello
# Hello