Beefy Boxes and Bandwidth Generously Provided by pair Networks
Problems? Is your data what you think it is?

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

by boftx (Deacon)
on Nov 26, 2013 at 19:54 UTC ( #1064459=note: print w/replies, xml ) Need Help??

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

Here is a code snippet with an approach using splice that might get you where you want (assume proper strictures, etc.):

my $element_size = 3; my $group_size = 10; #adjust as needed for 5th, 7th, etc. my $block_size = $element_size * $group_size; # since "elements" are v +irtual my @new; while ( @old_array ) { if ( @old_array < $block_size ) { # don't add new if old is too sm +all push(@new, @old_array); last; } push(@new, splice(@old_array,0,$block_size); # "shift" out of old push(@new,qw( create mount remove )); # new "element" added here } # UPDATE: added code to put remainder of @old_array onto @new if not # a full multiple.

The above code assumes that you only want to add a new "element" if a full multiple of "group_size" is present.

It helps to remember that the primary goal is to drain the swamp even when you are hip-deep in alligators.

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1064459]
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others about the Monastery: (3)
As of 2018-04-21 21:41 GMT
Find Nodes?
    Voting Booth?