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

Re: wipe out elements in an array

Thread Previous | Thread Next
Bryan R Harris
April 29, 2002 14:11
Re: wipe out elements in an array
Message ID:

Thanks to all for the tips, and for introducing me to the grep and splice

As a sidenote, I mucked around and discovered that for my purposes, just
assigning that element to "" works fine, since I'm just printing the
results back out to a file and the individual elements have their newlines
still attached.

Out of curiosity, do the $, $/ $\ variables maintain their values between
runs?  Or are they reset before running a new script?

- B


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

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