Beefy Boxes and Bandwidth Generously Provided by pair Networks
We don't bite newbies here... much
 
PerlMonks  

Re: Keeping a Count in foreach

by mfriedman (Monk)
on Jun 17, 2002 at 18:03 UTC ( [id://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
Domain Nodelet?
Node Status?
node history
Node Type: note [id://175148]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others drinking their drinks and smoking their pipes about the Monastery: (2)
As of 2024-04-26 04:47 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found