in reply to Inserting into an array while stepping through it

Processing the array in reverse as Zaxo suggests is probably the best way, unless you need to process it forwards.

If that's the case, you could reverse the array, reverse the list in the for and then reverse the array again when you've finished. reverse is quite amazingly efficient, so the overhead is lower than you might expect.

@array = reverse @array; for ( reverse 0.. $#array ) { splice @array, $_, 1, func( $array[$_] ); } @array = reverse @array;

Or you could replace the element of the array by a reference to the returned list and then flatten the array when the loop is complete.

for( 0 .. $#array ) { my @results = func( $array[$_] ); $array[$_] = @results > 1 ? $results[0] : \@results; } @array = map{ ref $_ ? (@$_) : $_ } @array;

It would be interesting to see which approach is the more efficient.


Examine what is said, not who speaks.
"Efficiency is intelligent laziness." -David Dunham
"When I'm working on a problem, I never think about beauty. I think only how to solve the problem. But when I have finished, if the solution is not beautiful, I know it is wrong." -Richard Buckminster Fuller


Replies are listed 'Best First'.
Re: Re: Inserting into an array while stepping through it
by tachyon (Chancellor) on Jun 13, 2003 at 10:25 UTC

    Or you could replace the element of the array by a reference to the returned list and then flatten the array when the loop is complete

    I liked that idea too. GMTA

    I expect it would also be faster (too lazy to test) as it is a classic link list solution and passes a minimal amount of data around, etc, etc. It will use roughy double the memory though when you flatten the list...

    cheers

    tachyon

    s&&rsenoyhcatreve&&&s&n.+t&"$'$`$\"$\&"&ee&&y&srve&&d&&print