in reply to foreach loop question

You are correct - a foreach loop builds a temporary list, and iterates over that. That means that when you loop over the keys of a hash using foreach, entries added inside the loop are not iterated over.

For 'one by one' iteration over a hash, have a look at each, but you cannot use that to add elements to the hash on the fly while iterating over it either (well, you can, but it's your foot :) ).

You'll have to iterate over the hash keys again if you want to get at the new values, I think.

CU
Robartes-

Replies are listed 'Best First'.
Re: Re: foreach loop question
by fletcher_the_dog (Friar) on Apr 16, 2003 at 21:38 UTC
    "You are correct - a foreach loop builds a temporary list, and iterates over that." I don't think this is true. Try this:
    my @list = (1,2,3,4,5); foreach (@list) { print $_."\n"; push @list,$_.$_; }
    This makes an infinite loop (at least until your memory runs out), so it appears that foreach is actually using the original list

      This is documented in perlsyn.

      If any part of LIST is an array, foreach will get very confused if you add or remove elements within the loop body, for example with splice. So don't do that.