develooper Front page | perl.beginners | Postings from April 2002

Re: wipe out elements in an array

Thread Previous | Thread Next
Peter Scott
April 25, 2002 17:38
Re: wipe out elements in an array
Message ID:
At 08:24 PM 4/25/02 -0400, Jeff 'japhy' Pinyan wrote:
>On Apr 25, Bryan R Harris said:
> >I'd like to remove all elements in an array that meet a certain criteria
> >without changing their order.  I'm sure this gets done all the time, but
> >I'm not sure how to do it...
>You want splice() instead.
>   perldoc -f splice

The poster appeared to want to remove possible discontiguous element sequences:

>>My guess (this is just an example):
>>@myarray = (1,2,3,4,5,6,7,8,9,10);
>>foreach (@myarray) { if ($_ == 3 || $_ == 5) { undef($_); } }
>>But I don't think it's working right...

Right, setting an element to undef does not remove it.

Use splice() if you want to remove a known number of elements that are all 
adjacent and start from a known offset.  Otherwise, use grep:

         @myarray = grep { $_ != 3 && $_ != 5 } @myarray

If you want to remove elements based upon some criteria applied to their 
*index*, use an array slice.
Peter Scott
Pacific Systems Design Technologies

Thread Previous | Thread Next Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at | Group listing | About