Beefy Boxes and Bandwidth Generously Provided by pair Networks
laziness, impatience, and hubris
 
PerlMonks  

Re^2: How foreach loops decide what to iterate through

by jvector (Friar)
on Feb 14, 2009 at 00:25 UTC ( #743742=note: print w/replies, xml ) Need Help??


in reply to Re: How foreach loops decide what to iterate through
in thread How foreach loops decide what to iterate through

That's clear and understandable, and what I would have thought too. (</metoo> ;-)

But I am still puzzled as to what is happening in the example of

my @a = (1); foreach (@a) { push @a, 1; }

Ceci n'est pas une signature

Replies are listed 'Best First'.
Re^3: How foreach loops decide what to iterate through
by jethro (Monsignor) on Feb 14, 2009 at 02:54 UTC

    You are looping over an array you are adding to, so you are never reaching the end.

    This is somewhat similar to the following loop

    my $i=1; my $end= 2; while ($i++<$end) { $end++; }

    Note that

    y @a = (1); foreach (sort @a) { push @a, 1; }

    stops immediately, because here you are looping over the anonymous array that is not expanding.

Re^3: How foreach loops decide what to iterate through
by jasonk (Parson) on Feb 15, 2009 at 18:33 UTC

    Essentially what you are doing is something like this:

    my @a = (1); for ( my $i = 0 ; $i <= $#a ; $i++ ) { push( @a, 1 ); }

    So the loop isn't being restarted or re-evaluated, but because you are extending the thing it's iterating over, it never gets to the end.


    www.jasonkohles.com
    We're not surrounded, we're in a target-rich environment!
      The insight moment for me in this thread was getting when it is that an anonymous array is created and used (and therefore the loop is unaffected by modifications to the original array during its execution) as opposed to the original array itself being used during the loop.

      Note to self: check copy of PBP to see if this is mentioned.


      Find "This signature" for less on Ebay

        an anonymous array is created and used

        An anonymous list, not an anonymous array. (Well, all lists are anonymous.) No array is created.

        Arguments and return values of functions and subs are placed on the stack as a list of scalars.

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others taking refuge in the Monastery: (2)
As of 2022-05-17 23:22 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    Do you prefer to work remotely?



    Results (68 votes). Check out past polls.

    Notices?