Beefy Boxes and Bandwidth Generously Provided by pair Networks
XP is just a number

Re: Common Perl Pitfalls

by JavaFan (Canon)
on Apr 09, 2012 at 23:16 UTC ( #964224=note: print w/replies, xml ) Need Help??

in reply to Common Perl Pitfalls

Deleting some array elements
I'd write that as:
@array = @array[grep {!should_delete($_)} 0..$#array];
If only because your splice solution can be quadratic worst case, while the above is linear (assuming should_delete has a running time bounded by a constant).

Replies are listed 'Best First'.
Re^2: Common Perl Pitfalls
by Joe_ (Beadle) on Apr 09, 2012 at 23:24 UTC

    That's a really great one, too.
    I've only recently started coming to grips with grep and map. I've always felt that this problem can be tackled by a one-liner but I just couldn't put my hands on it. Thanks for finally providing it :)

Re^2: Common Perl Pitfalls
by Joe_ (Beadle) on Apr 09, 2012 at 23:50 UTC

    Care to elaborate on that "quadratic" comment? How do you figure? I'm not that good with complexity theory, I'm afraid...

      Care to elaborate on that "quadratic" comment?
      Say you want to delete all elements in the second half of the array. The first N/2 iterations of your loop, no splicing happens. But on the N/2 + 1st iteration, the splicing takes at least N/2 - 1 steps, as that many array elements need to be moved. On the N/2 + 2nd iteration, the splicing takes at least N/2 - 2 steps. In total, you will be moving


      array elements. If I've done my math correctly, the above sum equals (N2 - 2N + 4)/8. Which means your algorithm runs in Ω(N2) time.

        Wonderful. Thanks for enlightening me...

Log In?

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

How do I use this? | Other CB clients
Other Users?
Others lurking in the Monastery: (6)
As of 2016-10-24 08:42 GMT
Find Nodes?
    Voting Booth?
    How many different varieties (color, size, etc) of socks do you have in your sock drawer?

    Results (304 votes). Check out past polls.