Beefy Boxes and Bandwidth Generously Provided by pair Networks
Just another Perl shrine
 
PerlMonks  

Re: for loop syntax difference

by toolic (Bishop)
on Aug 28, 2009 at 14:00 UTC ( #791907=note: print w/replies, xml ) Need Help??


in reply to for loop syntax difference

Here is a quote from the official Perl documentation (For Loops):
And it's faster because Perl executes a foreach statement more rapidly than it would the equivalent for loop.
I believe the "for" in the docs refers to a C-style loop (for($i=0;$i<10;$i++)) and the "foreach" refers to the more Perlish style (for $i (1..10)).

To prove that it is faster for you, you would have to benchmark it, as someone else already explained to you in another forum. It is considered good etiquette to mention that you already asked this question elsewhere.

Replies are listed 'Best First'.
Re^2: for loop syntax difference
by Taulmarill (Deacon) on Aug 28, 2009 at 14:05 UTC
    I believe the "for" in the docs refers to a C-style loop (for($i=0;$i<10;$i++)) and the "foreach" refers to the more Perlish style (for $i (1..10)).

    Yes, however for and foreach are interchangeable since perl automatically detects which one to use.
      Also from the official Perl documentation (For Loops):
      The foreach keyword is actually a synonym for the for keyword, so you can use foreach for readability or for for brevity.

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others browsing the Monastery: (2)
As of 2023-06-02 21:28 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found

    Notices?