Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl Monk, Perl Meditation
 
PerlMonks  

Union of hashes

by IvorW (Initiate)
on Feb 07, 2002 at 10:58 UTC ( [id://143846]=perlquestion: print w/replies, xml ) Need Help??

IvorW has asked for the wisdom of the Perl Monks concerning the following question:

Is there an easy way of getting the union of 2 hashes? I know this can be done longhand with a loop, but I wondered if there was a better way.

foreach (keys %a)
{
    $b{$_} = $a{$_};
}

While this works, I wondered if there was a better way. I know the equivalent with arrays is easy.


@b = (@b,@a);

This might become significant for performance if one or other hash is not a real hash, but is tied to something.

Any thoughts?

Replies are listed 'Best First'.
Re: Union of hashes
by Biker (Priest) on Feb 07, 2002 at 11:07 UTC

    If you're happy to create a new hash from the two existing ones, the following should work:

    %new_hash=(%a,%b);
    I believe that this should work, but test it first:
    %a=(%a,%b);
    "Livet är hårt" sa bonden.
    "Grymt" sa grisen...

      Or, for no particular reason that I can think of :

      @a{keys %b} = values %b;

      Assuming that keys and values are guaranteed to return in the same order :)

      /J\

        They are guaranteed to be in the same order. Note though that in both your solution and Biker's solution this is a union of keys. Entries in %b will overwrite entries in %a with their values when they share the same key. There's really no way around this, and it's probably what IvorW wants, but I thought I'd mention it for safety's sake.
Re: Union of hashes
by trs80 (Priest) on Feb 07, 2002 at 20:50 UTC
Re: Union of hashes
by ropey (Hermit) on Feb 07, 2002 at 16:24 UTC
    map {$b{$_} = $a{$_}} keys %a;
    Does a similar thing
      Only in the sense that
      print "hello world";
      and
      print $_ for split //, "hello world";
      do "similar things". The void map solution is to be avoided, especially when there are so many better solutions.

      -- Randal L. Schwartz, Perl hacker

        Like masem's most excellent Hash::Merge. It does deep hashes, and optionally does true copies instead of references.

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others drinking their drinks and smoking their pipes about the Monastery: (8)
As of 2024-04-23 12:52 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found