in reply to Keeping a Count in foreach

Can I do this using the foreach structure easily or will I have to resort to a for loop?

There is no real difference between for and foreach, except for convention. From perlsyn:

The foreach keyword is actually a synonym for the for keyword, so you can use foreach for readability or for for brevity.

So,

perl -e 'foreach my $dir(@INC) { print "$dir\n"; }' perl -e 'for my $dir(@INC) { print $dir\n"; }'

Are exactly the same, as are

perl -e 'foreach($i = 0; $i < 10; $i++) { print "$i\n"; }' perl -e 'for($i = 0; $i < 10; $i++) { print "$i\n"; }'

Replies are listed 'Best First'.
for != foreach
by Util (Priest) on Jun 18, 2002 at 03:14 UTC
    Yes, but the first two are completely different from the last two. We have to call these control structures *something*. When talking about them, we call the first two "foreach loops", and the last two "for loops", regardless of which keyword is used. perlsyn follows this convention in its =head2 headers, and arunhorne is using it in his question.
    $ perl -MO=Deparse,p -e 'for(@z){print}' foreach $_ (@z) { print $_; } -e syntax OK