in reply to Re^3: removing elements in array in perl
in thread removing elements in array in perl
That can be slightly simplified due to the way splice handles a negative OFFSET:
(If $n is greater than the number of elements of the array, a run-time error is thrown.)c:\@Work\Perl\monks>perl -wMstrict -le "use Data::Dumper; ;; my @A1 = qw(a b c d e f g); my $n = 2; my @A2 = splice @A1, -$n; ;; print Dumper [\@A1, \@A2]; " $VAR1 = [ [ 'a', 'b', 'c', 'd', 'e' ], [ 'f', 'g' ] ];
Update: Actually, the negative offset approach might be significantly better because it throws an error whenever $n is greater than the number of array elements, whereas the
splice @A1, @A1-$n, $n
expression produces a silent, possibly unexpected/undesirable aliasing behavior for some values of $n > @array and doesn't throw an error until $n is greater than twice the number of elements of the array.
c:\@Work\Perl\monks>perl -wMstrict -le "use Data::Dump qw(dd); ;; my @A1 = qw(a b c d e f g); my $n = 14; my @A2 = splice @A1, @A1-$n, $n; ;; dd \@A1, \@A2; " ([], ["a" .. "g"]) c:\@Work\Perl\monks>perl -wMstrict -le "use Data::Dump qw(dd); ;; my @A1 = qw(a b c d e f g); my $n = 15; my @A2 = splice @A1, @A1-$n, $n; ;; dd \@A1, \@A2; " Modification of non-creatable array value attempted, subscript -8 at - +e line 1.
Give a man a fish: <%-{-{-{-<
|
|---|