in reply to changing array size in foreach loop: is it safe?

I think a clean and clear way to do this is with a while loop, maintaining your own index. Something like this:
my $i = 0; while ($i <= $#foo) { push @foo, 'h' if $foo[$i] eq 'd'; print $foo[$i]; $i++; }

Replies are listed 'Best First'.
Re^2: changing array size in foreach loop: is it safe?
by Errto (Vicar) on Feb 08, 2005 at 05:59 UTC
    It occurred to me that in my real code I don't actually need the value of @foo afterwards, so I should just use shift:
    while (@foo) { my $x = shift @foo; push @foo, 'h' if whatever(); }