in reply to changing array size in foreach loop: is it safe?
The iterator keeps marching through the d's, adding new ones to the end. A better way to do it might be:my @foo = qw/a b c d e f g/; for my $x (@foo) { push @foo, 'd' if $x eq 'd'; print $x; }
I doubt that it's implmentation-dependent. The iterator is stepping through the array, and by the time it gets to the end of the array, there's another element there to step through.push @foo, map {$_ eq 'd' ? 'd' : ()} @foo; print for @foo;
Still, it's not a nice trick to play. Here's an even more diabolical one:
for (@foo) { print; shift(@foo) if $_ eq 'c'; } print "\n@foo\n";
|
|---|