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.
|
|---|
| 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 |