Reputation: 22695
Is there an easy way to remove n consecutive elements of a Perl array (thus making it shorter in length)?
Upvotes: 2
Views: 8095
Reputation:
As the other answers indicated, splice
works. As an alternative approach (TIMTOWTDI, after all), if you have the upper and lower indices for the n
consecutive elements that you want removed, then you can do it via grep
and an array slice. For example:
use strict;
use warnings;
my @a=("a".."z");
#We will remove the letters "e" through "u"
my $lower=4;
my $upper=20;
print "$_\n" foreach(@a[grep{$_<$lower or $_>$upper}0..$#a]);
The output is:
a
b
c
d
v
w
x
y
z
Upvotes: 0
Reputation: 40142
You are looking for the Perl builtin function splice, which lets you pick a starting point, number of elements to remove, and an optional replacement list.
my @array = 0 .. 9;
my @slice = splice @array, 3, 3;
say "@slice"; # prints "3 4 5"
say "@array"; # prints "0 1 2 6 7 8 9"
say 0 + @array; # prints 7
Upvotes: 15