On 4/9/07, Jean-Rene David <[EMAIL PROTECTED]> wrote:
* Chas Owens [2007.04.09 11:00]:
> >       for (my $i = 0; $i < @banks; $i++)
>
> If you must loop this way at least do it like this:
>
> for my $i (0 .. $#banks) {}
>
> But most likely you don't need to loop that way and it is better to
> loop this way:
>
> for my $bank (@banks) {}

I've been wondering: is the array guaranteed to be
traversed in the same order in all three cases?

All three loops process the array in the same order (from index 0 to
index $#array).  The benefit of the index-less version is that you
cannot make an off-by-one-error.  Examine the following loops:

for (my $i = 1; $i < @banks; $i++)
for (my $i = 0; $i <= @banks; $i++)
for (my $i = 1; $i <= @banks; $i++)
for my $i (0 .. @banks)
for my $i (1 .. @banks)
for my $i (1 .. $#banks)

How easy do you think it will be to find the error?  What if the code
seems to be doing the right thing?  It is much safer to say

for my $bank (@banks)

You know for certain that each element of @array will be visited.

It is also important to note that there is no difference between $bank
and $banks[$i].  If you modify $bank then the corresponding element in
@banks is also modified.


And are the latter two really "for" and not
"foreach"?
snip

foreach is now only an alias for for, if that makes any sense.  They
used to have separate functionality, but somewhere around 5.6 they
were merged.  The term foreach is only kept around for legacy code;
new code should use for.

--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/


Reply via email to