in reply to Re: Re: Inserting into an array while stepping through it
in thread Inserting into an array while stepping through it

I don't see the problem. The iterator is bumped to 4, but at the beginning of the next iteration, it'll be 5. You could even put the 'bump' into a continue block (assign '2' to $bump, but don't increment $i untill the continue block). If the array is size zero, then it gets bumped by -1. The only problem I see is directly splicing in a function returning an array. You couldn't do that; you'd have to return a temp array first, get the size, then splice in the temp array. I don't understand what you say about splicing in a copy of the original. Do you want to recursively replace elements or not? I was assuming not. If you do, then I'd change my answer (and alot of other answers in this thread would have to change also).

But I see lots of other good answers in this thread anyway :)

Update: Correction, you can't have a continue block with a C-style for loop. But here's some example code which works:

my @arr = qw(abc aaa ccc bbb ddd); for (my $i=0; $i<=$#arr; $i++) { my @tmp = replace($arr[$i]); splice @arr, $i, 1, @tmp; $i += $#tmp; } print "@arr\n"; sub replace { local $_ = shift; return /^aaa$/ ? qw(rep1 rep2 aaa) : /^bbb$/ ? () : $_; }