Beefy Boxes and Bandwidth Generously Provided by pair Networks
Do you know where your variables are?

Re: how do I efficiently remove one hash from another?

by davido (Archbishop)
on Nov 27, 2012 at 07:11 UTC ( #1005803=note: print w/replies, xml ) Need Help??

in reply to how do I efficiently remove one hash from another?

Whether the loop is explicit, or implicit, there's a loop. But one cool means is:

delete @hash1{ keys %hash2 };

...which is pretty much the same thing as...

delete $hash1{$_} for keys %hash2;

...but with an implicit loop (via the hash slice) rather than the explicit 'for' loop. Note in either case, there's no need to worry about checking exists: delete doesn't complain if the element doesn't already exist.


Replies are listed 'Best First'.
Re^2: how do I efficiently remove one hash from another?
by tobyink (Abbot) on Nov 27, 2012 at 10:26 UTC

    The former compiles to a much smaller op tree than the latter:

    perl -MO=Concise -e'delete @hash1{keys %hash2}' perl -MO=Concise -e'delete $hash1{$_} for keys %hash2'

    On my machine, the slice performs about 20% faster than the loop.

    perl -E'sub Monkey::do{say$_,for@_,do{($monkey=[caller(0)]->[3])=~s{::}{ }and$monkey}}"Monkey say"->Monkey::do'
      The slice option only calls delete once. It also doesn't have to go the trouble of assigning $_ for each element. So that makes sense.

      When's the last time you used duct tape on a duct? --Larry Wall
Re^2: how do I efficiently remove one hash from another?
by perltux (Scribe) on Nov 27, 2012 at 07:18 UTC
    Thanks for the detailed explanation.

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1005803]
[Corion]: But I should do a mock-up program so that others can see what I'm talking about ;)
[robby_dobby]: Corion: I hope you know all too well that passing around "fancy" datastructures is a recipe for disaster :-)
[robby_dobby]: As in, it's-too-fancy- that-it-will-be- messy-to-handle
[choroba]: bit vectors as keys?
[robby_dobby]: Hmm, I keep falling asleep at my desk, while maintaining an active appearance. Am I getting old?
[robby_dobby]: Every time I fall asleep, there's a small guy in the dreams, shouting "Whoo!" and it jolts me awake. :/
[Lady_Aleena]: robby_dobby, at least you aren't driving. I seem to always be driving somewhere in my dreams and end up at a weird house.
[robby_dobby]: LA: That's there. But this is work and it's the same thing as falling asleep driving :-)

How do I use this? | Other CB clients
Other Users?
Others browsing the Monastery: (5)
As of 2017-05-29 08:04 GMT
Find Nodes?
    Voting Booth?