How can I delete elements from a Perl array?
I have a pretty big array and I want to delete the 2nd, 8th, 14th etc. element from an array. My array currently is like this:
Element1 x A B C
Element 2 y A B C
Element 3 z A B C
Broadly, I want to delete the x, y and z (just as an example, my array is slighly more complex). And pull up the rest. As in, I don't want to have a blank space in their positions. I want to get:
Element 1 A B C
Element 2 A B C
Element 3 A B C
I tried to giv开发者_开发百科e this a try with my array "todelete":
print "#Before Deleting"; print
$todelete[0]; print "\n"; print
$todelete[2]; print "\n"; print
$todelete[3];
for ($count=2; $count<@todelete;
$count=$count+6) { delete
$todelete[$count]; }
print "#After Deleting"; print
$todelete[0]; print "\n"; print
$todelete[2]; print "\n"; print
$todelete[3];$todelete[3];
But, currently, I think it just unitializes my value, because when I print the result, it tells me:
Use of uninitialized value in print
Suggestions?
The function you want is splice
.
delete $array[$index]
is the same as calling $array[$index] = undef
; it leaves a blank space in your array. For your specific problem, how about something like
@array = @array[ grep { $_ % 6 != 2 } 0 .. $#array ];
You can also use grep
as a filter:
my $cnt = 0;
@todelete = grep { ++$cnt % 6 != 2 } @todelete;
精彩评论