in reply to Inserting into an array while stepping through it

foreach isn't what you want here. Assuming you don't want to examine what you've just inserted:
my @a = qw( 1 3 2 4); # NOT TESTED MUCH $i = 0; while ($i < @a ) { if ($a[$i] == 2) { my @in = mysub(whatever); splice @a, $i, 1, @in; $i += @in ; } else { $i++; } } print "@a\n"; sub mysub { # whatever return ( qw(9 2 9)); # always return an array, even if only 1 element }
Update: removed parens in $i += ( @in ); though it seems to work.

--Bob Niederman, http://bob-n.com

Replies are listed 'Best First'.
Re: Re: Inserting into an array while stepping through it
by Anonymous Monk on Jun 13, 2003 at 12:22 UTC
    That works fine, Bob.

    I was hoping to avoid using an index. I'm of the school of thought that the fewer variables a program has - especially global variables, see http://c2.com/cgi/wiki?GlobalVariablesAreBad - the easier it is to understand and maintain.

    Still, this gets me over that hurdle ;-)

      I just wanted to point out that the index ($i) does not have to be global. You could write:

      while (my $i < @a)

      ... and have $i scoped to the while loop. Check out Lexical scoping like a fox.