Perl for loop statement is like the for statement from C or Java language and its behavior is almost the same. This short tutorial will show you a few code examples about how to use it in your Perl scripts. The syntax form of this statement is as follows:
LABEL for(initialization; test; re-initialization) BLOCK
This statement is a C-style loop and be cautious not to mix it with the foreach statement that is very often spelled by Perl programmers as for. When the Perl interpreter will meet a for statement it will know through syntax and context if it’s about the C-style loop or the more perlish foreach loop. Well, if inside the parentheses that follow the word for will be two semicolons (;) that separate the arguments, that means we have a genuine for statement and not a foreach one. As you have seen, the Perl for statement is preceded by a LABEL which can be very useful when you want to alter the normal flow within the block by using the loop controls (next, last or redo). Like other compound statements, the Perl for loop statement is implemented rather in terms of blocks than of statements. That means that the curly braces of the block are mandatory and can’t be omitted.
I want to mention here that there is not a short form or a statement modifier for the for statement as we have for other control statements: if, unless, while, until and foreach.
The Perl for statement argument section (enclosed in parenthesis) is composed of three parts:
- initialization – where you can initialize some counter variables; this part is executed only once at the beginning of the for statement
- test – represents a conditional expression that will be evaluated and if it is true, the block will be executed, otherwise the for loop will be terminated
- re-initialization – in this part the test expression will be reinitialized before the next iteration of the loop statement (like incremented or decremented a test variable in the most simple case)
The next snippet code will show you a simple for statement:for($i = 5; $i >= -5; $i--) {
print "$i "
}
print "\n";
# expected: 5 4 3 2 1 0 -1 -2 -3 -4 -5
First, the variable $i is initialized with 5. Next, Perl will check up to see if the condition is true, i.e. if $i is greater or equal to -5. If the condition is true, the script will print the value of $i and next will decrement $i. The process will continue as long as the condition is evaluated true. In our example the loop will exit when $i becomes less than -5.Well, you can simplify the above code, rewriting it as follows:
print "$_ " for(-5..5);
print "\n";
# expected: -5 -4 -3 -2 -1 0 1 2 3 4 5
We used the concatenating operator (..) and the special variable $_, here. The output is slightly different than in the previous example (compared to the precedent example, the numbers are printed in a reverse order).By the way, did you notice the trick? The Perl for statement from this example is not the genuine for statement we are speaking about, but foreach that is spelled for. The two semicolons are omitted from within the argument section of the Perl statement, and Perl interpreter will know that it is a foreach statement.
If the test expression will always be true, the Perl for statement will never end and you will face up an infinite loop. You can omit any of the three sections, but not the two semicolons. In the next sample code all the three sections are missing, and we’ll have an infinite loop:
$i = 0;
for (;;) {
$i++;
}
This code will run for ever or at least until Perl will throw an exception or you'll cancel it. You can modify the above code in order to exit from the loop, using the last control:$i = 0;
for (;;) {
$i++;
last if $i > 10;
}
print "i = $i\n"; # expected i = 11
The next example will show you how to print the keys of a hash structure and find out how many elements it has:# initialize a hash (associative array)
%ages = (John => 22, Harry => 25, Anne => 51);
# put the names in an array
@names = keys(%ages);
for($count = 0; @names; $count++) {
print shift @names;
print " ";
}
print "\nThe hash has $count elements\n";
and the output of this script sample:Anne John Harry
The hash has 3 elements
In the initialization section we assigned our counter to 0. We used the re-initialization section to increment the $count scalar variable which in our example has nothing to do with the test condition; at each iteration step, the program will remove and print the first element of the @names array. The loop will exit when the test condition will be evaluated false, i.e. the @names array will have no more elements (when @names is evaluated false). The last example is only an illustration about how you can use the Perl for statement, for arrays and hashes the foreach statement (which can be spelled for) is more appropriate.
NEW!!!
Do you want more information about the basic Perl topics?
Check my new "Perl How To" Tutorial eBooks page where I'll answer the most frequent questions regarding some topics :