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

I tried that.

Suppose my orginal array is
( a, aba, aaa, aca, bbb, abc )
Suppose my trigger for change is when the elements of the line are all the same - "aaa".

So index goes 0, 1, 2

At index = 2 I splice in 3 lines to replace it, so my array now looks like

( a, aba, replacement1, repalcement2, replacement3, aca, bbb, abc)

Next iterator is index=4, which gives me "replacement2" instead of "aca".

If I'm using something like:

splice(@array, $i, 1, func($array[$i]);
(which I am) and it can return a list the size of which is going to depend on context (such a hw previous eleements of the array had been treated - think of an order form where discount is by group and volume), then the juggling of the index counter is pretty hairy. I've tried this. The resulting code is very far from elegnant and my test harness easily "breaks" it, not least of all when the returned value is an empty list and the primary array gets shrunk. The iterator misses a line! However the worst case is when the replacement is two elements and the second element is a copy of the original. (Think about that!)

Replies are listed 'Best First'.
Re: Re: Re: Inserting into an array while stepping through it
by runrig (Abbot) on Jun 13, 2003 at 15:04 UTC
    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$/ ? () : $_; }