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.