Beefy Boxes and Bandwidth Generously Provided by pair Networks
more useful options

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]
[choroba]: megalag :-(
[erix]: ok, I looked it up, should have been: "Haribo macht Kinder froh und Erwachsene ebenso"
[Discipulus]: also mixing pizza (fermented/levited ) with juices is not so good
[erix]: D.: yeah, I am in the low countries. To be precise, I am 0.5m above sea level
[erix]: going for a run in the dunes - unless the storm (well, Beaufort 7) gets fiercer
Discipulus had stew with tomato sauce, onions, carrots and potatoes + bottle of red wine and still warm bred.. slept as dynosaur

How do I use this? | Other CB clients
Other Users?
Others cooling their heels in the Monastery: (10)
As of 2017-11-22 09:10 GMT
Find Nodes?
    Voting Booth?
    In order to be able to say "I know Perl", you must have:

    Results (316 votes). Check out past polls.