zigdon has asked for the wisdom of the Perl Monks concerning the following question:
I was talking to a friend about foreach aliasing the loop variable one by one through the list provided... As he was playing around with it, came across this:
Which produces:use Data::Dumper; @headers = ("header 1","header 2","header 3"); @body = ("body A","body B","body C"); $h = 4; foreach (@headers,"",@body) { print "$h: $_\n"; @body = (); push @headers,"header ".$h++; } print "\n", scalar @headers, "\n", Dumper \@headers;
4: header 1 5: header 2 6: header 3 7: 8: header 4 9: header 5 10: header 6 10 $VAR1 = [ 'header 1', 'header 2', 'header 3', 'header 4', 'header 5', 'header 6', 'header 7', 'header 8', 'header 9', 'header 10' ];
And I say huh? I follow until output line "7:". I can even see why it would run 3 more times (since the list fed to foreach was evaluated before @body was modified).
What I don't get is how the next 3 elements of @headers get in there? Is this part of the "don't mess with the loop vars while looping" clause?
What am I missing?
-- zigdon
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Mutable foreach list?
by Fletch (Bishop) on Jan 11, 2007 at 15:27 UTC | |
by zigdon (Deacon) on Jan 11, 2007 at 15:57 UTC | |
|
Re: Mutable foreach list?
by almut (Canon) on Jan 11, 2007 at 15:35 UTC | |
by zigdon (Deacon) on Jan 11, 2007 at 15:38 UTC | |
by ikegami (Patriarch) on Jan 11, 2007 at 18:16 UTC | |
by almut (Canon) on Jan 11, 2007 at 15:52 UTC |