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 | |
by merlyn (Sage) on Jun 18, 2002 at 03:21 UTC |