Beefy Boxes and Bandwidth Generously Provided by pair Networks
Clear questions and runnable code
get the best and fastest answer
 
PerlMonks  

Re: Adding an new element after every 5th element in array

by Cristoforo (Curate)
on Nov 26, 2013 at 19:22 UTC ( [id://1064449]=note: print w/replies, xml ) Need Help??


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

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://1064449]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others taking refuge in the Monastery: (3)
As of 2024-04-19 21:29 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found