Perl has a while statement that’s very similar to C’s. The basic syntax is
while (condition) {
# Body of the loop which is executed when "condition" is true
}
The last statement exits a loop, much like a C break statement. For example, Listing 2.8 computes the square of the first 10 integers.
use strict; use warnings; my $number = 1; # The number we are looking at my $square; # The square of the number while (1) { $square = $number ** 2; print "$number squared is $square "; ++$number; if ($number > 10) { last; } } |
To start a loop over, use the next statement. This is the equivalent of the C statement continue.
The for statement in Perl works much like the C version. It has three parts: an initialization statement, a limit expression, and an increment statement. Listing 2.9 shows an example.
use strict; use warnings; my $number; my $square; for ($number = 0; $number <= 10; $number++) { $square = $number ** 2; print "$number squared is $square "; } |