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 |