David L. Nicol writes:
 > Why not use an explicit perl5 counter?
 > 
 >     my $index;
 >     foreach $item (@array){ $index++;
 >          print $item, " is at index ", $index, "\n";
 >     }

Well, one reason is that your example doesn't work (it starts the
index at 1 instead of 0).  You'd need to do

    my $index = -1;
    foreach $item (@array){ $index++;
         print $item, " is at index ", $index, "\n";
    }

to get it to work.  But that would break if you had a `redo' in the
loop (it would increment $index when it shouldn't).  You could fix
that by moving the increment to the end of the loop:

    my $index = 0;
    foreach $item (@array){
         print $item, " is at index ", $index, "\n";
         ++$index;
    }

But that would break if you had a `next' (it wouldn't increment $index
when it should).  The correct way to do this is:

    my $index = 0;
    foreach $item (@array){
         print $item, " is at index ", $index, "\n";
    } continue {    
         ++$index;
    }

And you still couldn't be sure that $index really was what it claimed
to be except by carefully examining the loop body (easy for this
trivial loop, but not necessarily so).  With the explicit counter,

    foreach $item $index (@array) { ... }

$index could (and should) be a read-only variable (like $i is in
"foreach $i (1,2,3,4)").  This would make sure that it really was the
index it claimed to be.

-- 
Chris Madsen              http://www.trx.com      [EMAIL PROTECTED]
TRX Technology Services                                 (214) 346-4611

Reply via email to