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;
In reply to Re: Adding an new element after every 5th element in array
by hdb
in thread Adding an new element after every 5th element in array
by dvinay
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |