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

Difference between for and foreach

by dilip_val (Acolyte)
on Sep 17, 2007 at 14:41 UTC ( [id://639417]=perlquestion: print w/replies, xml ) Need Help??

dilip_val has asked for the wisdom of the Perl Monks concerning the following question:

Hi,
Can anyone please tell me the exact difference between "for" and "foreach" ?
Regards,
Jude

Replies are listed 'Best First'.
Re: Difference between for and foreach
by Joost (Canon) on Sep 17, 2007 at 14:54 UTC
Re: Difference between for and foreach
by n8g (Sexton) on Sep 17, 2007 at 14:49 UTC
Re: Difference between for and foreach
by johngg (Canon) on Sep 17, 2007 at 15:10 UTC
    There are two types of for loop in Perl, the C-style one

    for ($x = 1; $x <= 10; $x ++) { ... }

    and the other sort

    for $x ( 1 .. 10 ) { ... }

    Both can be written with foreach instead of for as the former is just a synonym for the latter. See the sections on loops in perlsyn.

    Cheers,

    JohnGG

Re: Difference between for and foreach
by Hercynium (Hermit) on Sep 17, 2007 at 15:42 UTC
    I'm pretty certain that Joost is correct at least as far as the specifications of how each construct is supposed to work.

    I'd like to add that it's worth paying attention to the aliasing behavior in certain situations, where the loop iterator variable ($thing in this example)
        for my $thing (@things) { # do stuff to $thing # }
    is not a copy of the current element of @things but more like a reference (a magic one that does not need to be de-referenced). The side effects have bitten me in the past, before I learned better :)

    Also, I've just been reading Perl Best Practices by TheDamian and chapter 6 (around pg. 100) goes in-depth on some of the techincal *and* psychological implications of different ways of using for and it's brethren.
      I've been caught out in the past by expecting to be able to rely on changes to the loop variable being preserved once the loop has terminated. For example, perhaps you want to know at which iteration a foreach loop terminated early using a last. However, the loop variable is localised inside the loop so that it reverts to it's old value after the loop.

      $ perl -Mstrict -Mwarnings -le ' > my $x = 0; > print $x; > for $x ( 1 .. 10 ) > { > my $y = rand; > print qq{$x -- $y}; > last if $y > 0.85; > } > print $x;' 0 1 -- 0.820319728766666 2 -- 0.070987764836417 3 -- 0.632845876776752 4 -- 0.195428179899814 5 -- 0.847997411282524 6 -- 0.353572570937089 7 -- 0.865375393672675 0 $

      You have to preserve the loop variable from inside the loop if you need to access it afterwards.

      Cheers,

      JohnGG

Re: Difference between for and foreach
by eyepopslikeamosquito (Archbishop) on Sep 17, 2007 at 21:07 UTC

    Notice that foreach has been removed from Perl 6. As specified in S04:

    There is no foreach statement any more. It's always spelled for in Perl 6, so it always takes a list as an argument...
    And the Perl 5 C-style for loop is now spelled loop. Quoting S04 again:
    The loop statement is the C-style for loop in disguise:
    loop ($i = 0; $i < 10; $i++) { ... }

      Maybe I'm just getting old and set in my ways, but it's things like this that make me dread the day Perl 6 replaces Perl 5...

Re: Difference between for and foreach
by andreas1234567 (Vicar) on Sep 17, 2007 at 18:31 UTC
    Time to revisit for vs foreach from the year 2000.

    perlsyn says:

    The foreach keyword is actually a synonym for the for keyword, so you can use foreach for readability or for for brevity.
    Update: I now see the link to for vs foreach was already mentioned by n8g above.
    --
    Andreas
      What about this bit then?

      And it's faster because Perl executes a foreach statement more rapidly than it would the equivalent for loop.

        That comment is about the C-style for loops ( e.g. for ( $i = 0; $i < $j; $i++) versus iterating directly over a list ( e.g. for my $item (@array)).
        Regarding the context, I would say "the equivalen for loop" means the C-style loop. The documentation should probably be improved there.
        لսႽ† ᥲᥒ⚪⟊Ⴙᘓᖇ Ꮅᘓᖇ⎱ Ⴙᥲ𝇋ƙᘓᖇ
A reply falls below the community's threshold of quality. You may see it by logging in.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://639417]
Approved by Corion
Front-paged by Corion
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others imbibing at the Monastery: (5)
As of 2024-04-24 11:02 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found