The Perl for loop is used to loop through a block of code until a specified condition is met. The for loop statement contains three sections followed by a block of code. Below is an example.
A Simple For Loop Example
for (my $number = 1; $number <= 10; $number++) {
print "$number ";
}
The first section initializes a variable
my $number = 1;
Then, the loop condition is provided. The loop will run as long as this is true.
$number <= 10;
Finally, the last section is executed at the end of each loop iteration. In our example's case, $number increments by one.
$number++
Executing this loop results in:
1 2 3 4 5 6 7 8 9 10
For Loop and Arrays
Here is an example of how the for statement can be used to loop through an array.
my @languages = ("Perl", "Python", "C", "Fortran");
my $size = @languages;
for (my $i = 0; $i <= $size; $i++) {
print "$languages[$i]\n";
}
Comments
There is very, *very* rarely
There is very, *very* rarely any reason to use a C-style for loop in Perl. Your examples would be done much more easily (and with much less chance of bounds-checking errors) with:
for my $number (1..10) {
print "$number ";
}
and
my @languages = ("Perl", "Python", "C", "Fortran");
for my $language (@languages) {
print "$language\n";
}
Or, if you need the index of the language for some other purpose,
my @languages = ("Perl", "Python", "C", "Fortran");
for my $i (0..$#languages) {
print "$languages[$i]\n";
}
+1 ;)
+1 ;)