in reply to splicing two arrays together
I wouldn't use splice at all. Instead I'd merge the two arrays:
#!/usr/bin/perl use strict; use warnings; my @first = qw(Can unlock secret); my @second = qw(you the code?); my @interleave; push @interleave, grep {$_} (shift @first), shift @second while @first || @second; print "@interleave";
Although you could use splice to do an "in place' merge:
#!/usr/bin/perl use strict; use warnings; my @first = qw(Can unlock secret); my @second = qw(you the code?); splice @first, @second, 0, pop @second while @second; print "@first";
or avoiding destroying the contents of @second:
... splice @first, $_, 0, $second[$_ - 1] for reverse 1 .. @second; print "@first";
or using splice to populate a new array:
my @new; splice @new, 0, 0, $first[$_], $second[$_] for reverse 0 .. $#second; print "@new";
Note that a few of these do stuff backwards to avoid having to account for elements that have been inserted into the target array.
Now, to answer your actual question. First lets add diagnostics a little differently to your existing code:
#!/usr/bin/perl use strict; use warnings; my @first = qw(Can unlock secret); my @second = qw(you the code?); dumpArrays('start', \@first, \@second); splice(@first, 1, 0, @second[0,-2]); dumpArrays('first', \@first, \@second); my @newArray = @first; splice(@newArray, 5,0,@second[0,2]); dumpArrays('na', \@first, \@second, \@newArray); my @newArray1 = @newArray; splice(@newArray1, 2,1); dumpArrays('na1', \@first, \@second, \@newArray1); my @newArray2 = @newArray1; splice(@newArray2, 4,1); dumpArrays('na2', \@first, \@second, \@newArray2); my @newArray3 = @newArray2; splice(@newArray3,3,0, @second[1,1]); dumpArrays('na3', \@first, \@second, \@newArray3); sub dumpArrays { my ($msg, @arrays) = @_; printf "%-10s %s\n", $msg, join '|', map {"@$_"} @arrays; }
Prints:
start Can unlock secret|you the code? first Can you the unlock secret|you the code? na Can you the unlock secret|you the code?|Can you the unlock +secret you code? na1 Can you the unlock secret|you the code?|Can you unlock secr +et you code? na2 Can you the unlock secret|you the code?|Can you unlock secr +et code? na3 Can you the unlock secret|you the code?|Can you unlock the +the secret code?
Note that the error doesn't happen until the very last step. In that step you splice(@newArray3,3,0, @second[1,1]);. @second[1,1] which inserts two copies of the word 'the'. You just needed $second[1] there.
|
|---|