You need to splice in elements starting from the end to the beginning. Otherwise, you will confuse
splice (as new items added to the front invalidates the following indices). (What used to be say, index 4 will get moved up 1 when a new item is added in front).
When you splice in from the end, you leave the preceding indices alone.
for my $i (reverse 0 .. $#array) {
if (($i+1) % 3 == 0) {
splice @array, $i+1, 0, "new item";
}
}
use Data::Dumper; print Dumper \@array;
Ah, I see
davido has the better solution - more efficient.