Beefy Boxes and Bandwidth Generously Provided by pair Networks
Your skill will accomplish
what the force of many cannot

Union of Two Hashes

by Rajiv (Initiate)
on Apr 09, 2002 at 13:37 UTC ( #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 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?

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

How do I use this? | Other CB clients
Other Users?
Others contemplating the Monastery: (2)
As of 2021-10-21 03:15 GMT
Find Nodes?
    Voting Booth?
    My first memorable Perl project was:

    Results (82 votes). Check out past polls.