Beefy Boxes and Bandwidth Generously Provided by pair Networks
Syntactic Confectionery Delight
 
PerlMonks  

Re: popping, shifting or splicing an array???

by revdiablo (Prior)
on Aug 09, 2005 at 17:30 UTC ( #482323=note: print w/replies, xml ) Need Help??


in reply to popping, shifting or splicing an array???

Your question is a bit vague, but if you're looking for the general purpose tool, it's splice. The others, shift and pop, can only perform a subset of what splice can do. Admittedly, this is a very useful subset that would be a hassle to use splice for all the time, but when you want general purpose you use general purpose.

In your case, it would be nice if you could collapse the user's selection into a set of ranges. If you don't want to do that, you could easily enough splice off one element at a time. The trick here is to iterate on the to-be-spliced indexes in descending order, otherwise you'll have to recalculate their new positions each time. Example:

my @array = (1 .. 1000); my @toremove = (7,1,6,5,3); for (sort { $b <=> $a } @toremove) { splice @array, $_, 1; }
# another way to to it: for (reverse sort @toremove) { ... }

Update: the Other Way was flawed. It didn't do a numeric sort.

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://482323]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others making s'mores by the fire in the courtyard of the Monastery: (8)
As of 2019-11-13 09:44 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    Strict and warnings: which comes first?



    Results (70 votes). Check out past polls.

    Notices?