in reply to Adding an new element after every 5th element in array

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.

Replies are listed 'Best First'.
Re^2: Adding an new element after every 5th element in array
by dvinay (Acolyte) on Nov 26, 2013 at 19:51 UTC

    Thanks for the solution, but i need one more change in requirement, instead of adding the new element after "remove", i need to add the new element say after every multiples of 10 set, i.e. 10th set, 20th set,30th set and 40th set.

    totally we have 20 sets right, i need to add one new element after 10th set and other one after 20th set

    How it can be achieved...?