Perl For loop
Perl for statement is used to execute a piece of code over and over again. Perl for statement is useful for running a piece of code in a specific number of times. Here is the Perl for statement syntax:
-
for(initialization; test; increment){
-
statements;
-
}
There are three elements in the for statement - initialization, test and increment - are separated by semicolons. Perl does the following sequence actions:
- Step 1. The initialization is expression is evaluated - you can initialize counter variable here.
- Step 2. The test expression is evaluated. If it is true, the block - statements - will be executed.
- Step 3. After the block executed, the increment is performed and test is evaluated again. The process go to step 2 until the test expression is false. If it is never false, you encounter with a indefinite loop.
Here is a code snippet to print a message 10 times.
-
for($counter = 1; $counter <= 10; $counter++){
-
print "for loop #$counter\n";
-
}
First the $counter is initialized. Next Perl checks if the $counter is less than or equal 10 or not. In this case, $counter is 1 so Perl executes the code inside block and increase the $counter into 1. The process takes place until the $counter variable is equal to 10 therefore the code block executed 10 times.
Perl allows you to omit the initialization and increment part of for statement. You can initialize outside the loop and increase control variable inside the block as follows:
-
$counter = 1
-
for(; $counter < 10;){
-
print "for loop #$counter\n";
-
$counter++;
-
}