1

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 give 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?

3 Answers 3

5

The function you want is splice.

Sign up to request clarification or add additional context in comments.

5 Comments

@poutine: someone is amazing because they have read the basic documentation that comes with every installation of perl? Isn't that setting the bar a little low?
Ah ... but now I face another problem, since the index has been shifted. The element, I need to delete is no more at position 8. Its now at position 7. Ah .. and the same for the rest. I think a better alternative would be to just delete the element, then use a filter and then splice those out? Ether ...your right. For a brief moment, when I thought it worked, I was amazed .. since I spent a lot of time trying to think about it in terms of a for loop.
@poutine, the traditional solution to that is to delete backwards. Instead of 2, 8, 14, ... go 14, 8, 2. That way, the indexes don't change before you reach the element.
Thanks cjm, but I used a work-around decrementing the index. A little more work, but I was able to get it going ..
Decrementing an index is tremendously ugly. Instead, I'd use a 'while' loop in which I either remove an element OR increment the counter... ... or remove them backwards.
2

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 ];

1 Comment

delete on arrays is deprecated--another good reason not to use it.
2

You can also use grep as a filter:

my $cnt = 0; @todelete = grep { ++$cnt % 6 != 2 } @todelete;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.