Beefy Boxes and Bandwidth Generously Provided by pair Networks
more useful options
 
PerlMonks  

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

by hdb (Monsignor)
on Nov 26, 2013 at 20:20 UTC ( [id://1064464]=note: print w/replies, xml ) Need Help??


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

I would use splice to remove a set from the beginning of the array and push it onto a new array. Repeat 10 times. push your new element onto the new array. Repeat until original array is exhausted.

use strict; use warnings; use Data::Dumper; my @array = ("create", "mount", "remove","create", "mount", "remove"," +create", "mount", "remove","create", "mount", "remove","create", "mou +nt", "remove","create", "mount", "remove","create", "mount", "remove" +,"create", "mount", "remove","create", "mount", "remove","create", "m +ount", "remove","create", "mount", "remove","create", "mount", "remov +e","create", "mount", "remove","create", "mount", "remove","create", +"mount", "remove","create", "mount", "remove","create", "mount", "rem +ove","create", "mount", "remove","create", "mount", "remove","create" +, "mount", "remove"); my $nset = 3; my $every = 10; my $newelement = "newelement"; my @newarray; while( @array ) { for( 1..$every ) { # for 10 times push @newarray, splice @array, 0, $nset; # push a set onto new arr +ay } push @newarray, $newelement; # add the new element } print Dumper \@newarray;

Replies are listed 'Best First'.
Re^2: Adding an new element after every 5th element in array
by boftx (Deacon) on Nov 26, 2013 at 20:32 UTC

    Nevermind, this is completely wrong. :(

    I think hdb's example could be simplified a bit plus avoid any old-size remainder problems like this:

    while( @array ) { push @newarray, splice @array,0,$nset; next if @newarray % ($nset * $every); # no need for a counter w +ith % op push @newarray, $newelement; # add the new element }
    It helps to remember that the primary goal is to drain the swamp even when you are hip-deep in alligators.

Log In?
Username:
Password:

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

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

    No recent polls found