Beefy Boxes and Bandwidth Generously Provided by pair Networks
Just another Perl shrine
 
PerlMonks  

Union of Two Hashes

by Rajiv (Initiate)
on Apr 09, 2002 at 13:37 UTC ( [id://157715]=perlquestion: print w/replies, xml ) Need Help??

Rajiv has asked for the wisdom of the Perl Monks concerning the following question: (hashes)

I want to find the union of two hashes. I tried the option of merging the two hashes, but found that relatively slower. Can anybody suggest me a good optimized code for getting the union of two hashes. The option that i am trying looks like this:
foreach $k (sort keys %hash1) { if (exists($hash2{$k})) { $matchWords++; } }
This snippet runs faster than merging. I don't understand how ??

Originally posted as a Categorized Question.

Replies are listed 'Best First'.
Re: Union of Two Hashes
by maverick (Curate) on Apr 09, 2002 at 14:35 UTC
    The question is a bit confusing...you ask for a union, but you code snippet looks like you're looking for the intersection. Union first. For small hashes this is really quick:
    %union = (%first, %second);
    For large:
    while (($k,$v) = each %first) { $union{$k} = $v; } while (($k,$v) = each %second) { $union{$k} = $v; }
    (makes sense once you consider the memory usage for the first snippet.

    For intersection, all you really need to do is change $matchWords to $matchWords{$k}++ the iterate of then matchWords looking for values == 2

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others goofing around in the Monastery: (1)
As of 2024-04-25 05:51 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found