in reply to How foreach loops decide what to iterate through

Both methods are practically the same in terms of speed. When you do foreach (sort @a), the foreach doesn't loop over @a but instead over the anonymous (and temporary) array that was returned from the sort function.

The only difference of the two methods is that the first method stores the (anonymous) sorted array into @a before going into the foreach loop, while the second method leaves the sorted array anonymous.

  • Comment on Re: How foreach loops decide what to iterate through

Replies are listed 'Best First'.
Re^2: How foreach loops decide what to iterate through
by jvector (Friar) on Feb 14, 2009 at 00:25 UTC
    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

      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.

      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