in reply to insert element into an array
Don't modify the array that you are for()'ing over. (Modifying the elements is fine, but inserting or deleting can have interesting interaction.)
Your code inserts # at the beginning of the array, not just before the "a", but once you find an "a", you move the a forward so you will find it on the next iteration of the loop, and then you do it again, and again... Try:
my @a = qw/x y z a b c e f g h i j/; my $skip; for (@a) { if ($_ eq "a" && ($skip = !$skip)) { splice @a, 0, 0, "#"; } }
If you really want the "#" just before the "a", something like this is a lot easier:
@a = map {$_ eq "a" ? ("#","a") : $_} @a;
|
|---|