Beefy Boxes and Bandwidth Generously Provided by pair Networks
Pathologically Eclectic Rubbish Lister
 
PerlMonks  

Re: Difference between for and foreach

by Hercynium (Hermit)
on Sep 17, 2007 at 15:42 UTC ( [id://639435]=note: print w/replies, xml ) Need Help??


in reply to Difference between for and foreach

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.

Replies are listed 'Best First'.
Re^2: Difference between for and foreach
by johngg (Canon) on Sep 18, 2007 at 09:00 UTC
    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

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others contemplating the Monastery: (4)
As of 2024-04-25 17:41 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found