Beefy Boxes and Bandwidth Generously Provided by pair Networks
There's more than one way to do things
 
PerlMonks  

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

by boftx (Chaplain)
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.


Comment on Re: Adding an new element after every 5th element in array
Select or Download Code

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others taking refuge in the Monastery: (7)
As of 2014-10-20 05:10 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    For retirement, I am banking on:










    Results (72 votes), past polls