in reply to for, foreach and $_...

The first example is the C style for loop with initialisation, condition and post-loop action in the preceding parens1. As for the second example that is the more natural way of iterating over lists in perl - it takes a list and aliases the topic ($_ by default) to each element per iteration. However in your second example, you create a list of values from 0 to the size of the array, as opposed to the last index of the array i.e
for(0 .. $#array) { ... }
This style is definitely the common way of iteratively accessing the elements of an array, but the more idiomatic approach of iterating over an array, when the index isn't needed, is simply
for(@array) { ... }
That works because an array in a list context flattens to a list (as opposed to in scalar context, where it yields the number of elements it contains, which is almost always $#array + 1) providing for with a list to iterate over.

See. perlsyn for more info.
HTH

_________
broquaint

1 internally, I believe this is implemented as a while(COND) { ... } continue { ... }

Replies are listed 'Best First'.
Re: Re: for, foreach and $_...
by larsen (Parson) on Aug 18, 2003 at 14:21 UTC
    internally, I believe this is implemented as a while(COND) { ... } continue { ... }
    Yes, it is:
    lorenzo@alice:~$ perl -MO=Deparse,-x3 -e 'for( my $i = 0; $i < 10; $i+ ++ ) {}' while ($i < 10) { ; } continue { ++$i } -e syntax OK