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

Your last description calls for reprocessing @extras until it is empty:
my @foo = qw/a b c d e f g/; my $sub = 'h'; for (my @extras = @foo; @extras; @extras = my @new_extras) { foreach my $x (@extras) { push @new_extras, $sub++ if $x =~ /[dhij]/; } push @foo, @new_extras; } print for @foo; # Tacks on h when it hits the d, then # i for the h, j for the i, and k for the j # yielding abcdefghijk
I like how the for replaces the bare block for scoping.

You can also do it without the @new_extras variable by replacing the foreach loop/push combination with a map:

my @foo = qw/a b c d e f g/; my $sub = 'h'; for (my @extras = @foo; @extras;) { @extras = map { /[dhij]/ ? $sub++ : () } @extras; push @foo, @extras; } print for @foo;

Caution: Contents may have been coded under pressure.