Perl for loop explained with examples

In this part of the Perl Tutorial we are going to talk
about the for loop in Perl. Some people also call it the C-style for loop,
but this construct is actually available in many programming languages.

Perl for loop

The for keyword in Perl can work in two different ways.
It can work just as a foreach loop works and it can act
as a 3-part C-style for loop. It is called C-style though
it is available in many languages.

I'll describe how this works although I prefer to write the foreach
style loop as described in the section about perl arrays.

The two keywords for and foreach can be used as synonyms.
Perl will work out which meaning you had in mind.

The C-style for loop has 3 parts in the controlling section.
In general it looks like this code, though you can omit any of
the 4 parts.

for (INITIALIZE; TEST; STEP) {
BODY;
}

As an example see this code:

for (my $i=0; $i <= 9; $i++) {
print "$i\n";
}

The INITIALIZE part will be executed once when the execution reaches that point.

Then, immediately after that the TEST part is executed. If this is false,
the whole loop is skipped. If the TEST part is true then the BODY is executed followed by
the STEP part.