"Perl for Perl Newbies" - Part 2The for LoopWhence for?

1.2. Whence for?

So far we have learned about three different kinds of for loops, so you are probably wondering when to use each one.

A substantial difference between the notation for($i=0 ; $i<$limit ; $i++)and between for $i (0 .. ($limit-1))is that the first accommodates itself to changes in $limit, while the second will iterate for a constant number of times. Of course, you can make the first one similar to the second by assigning the value of $limitto a third variable that will remain constant. Still, the second notation is usually safer from that sense.

The foreach $item (@array)loop is quite handy, but sometimes when iterating over an array of items the index of the item is of importance. In that case, one may prefer to use a normal forloop.

Written by Shlomi Fish