Beefy Boxes and Bandwidth Generously Provided by pair Networks
Do you know where your variables are?
 
PerlMonks  

Re: Keeping a Count in foreach

by mfriedman (Monk)
on Jun 17, 2002 at 18:03 UTC ( #175148=note: print w/replies, xml ) Need Help??


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

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://175148]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others scrutinizing the Monastery: (3)
As of 2021-06-18 01:46 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    What does the "s" stand for in "perls"? (Whence perls)












    Results (86 votes). Check out past polls.

    Notices?