* Bob Rogers <[EMAIL PROTECTED]> [2002-11-21 09:38]:
> From: darren chamberlain <[EMAIL PROTECTED]>
> Date: Thu, 21 Nov 2002 09:17:11 -0500
> > * Chris Devers <[EMAIL PROTECTED]> [2002-11-20 16:19]:
> > > On Wed, 20 Nov 2002, darren chamberlain wrote:
> > > > I think the answer is to use a C-style for loop:
> > > >
> > > > for (my $i = 0; $i < $#array; $i++) {
> > > > # $i is your "iterator"
> > > > # $array[$i] is the "current" element
> > > . . .
> > > Is there any significant difference, beyond style preference?
> >
> > My C-style for loop (above) is identical to:
> >
> > my $iterator = 0;
> > while ($iterator < $#array) {
> > $iterator++;
> > do "stuff";
> > }
> >
> > . . .
>
> Not quite. It looks like the 'while' loop skips element 0, but the
> 'for' version skips the last one. I tend to prefer "$i < @array" over
> "$i <= $#array" in loop tests, because I think it is more natural and
> less prone to such problems.
Yes, the while condition needs to be either <= $#array or < @array, but
the while loop only skips element 0 only because the body of the loop
(the *example*) isn't robust (I thought that do "stuff" would be a clue
;). Move the incrementation to the end, and fix the conditional, and it
Does The Right Thing:
my @array = qw(1 2 3 4 5);
my $iterator = 0;
while ($iterator < @array) {
print "\$array[$iterator] => $array[$iterator]\n";
$iterator++;
}
Gives:
$array[0] => 1
$array[1] => 2
$array[2] => 3
$array[3] => 4
$array[4] => 5
(darren)
--
I accept chaos. I'm not sure whether it accepts me. I know some people
are terrified of the bomb. But then some people are terrified to be
seen carrying a modern screen magazine. Experience teaches us that
silence terrified people the most.
-- Bob Dylan
_______________________________________________
Boston-pm mailing list
[EMAIL PROTECTED]
http://mail.pm.org/mailman/listinfo/boston-pm