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

Does anyone know how to add to a pre-existing hash so that the original hash merges with the added data and grows to encompase both the new and old data? IE %A + %B = %C where A = ('a' => 1) B = ('b' => 2) C = ('a' => 1, 'b' => 2,)

Replies are listed 'Best First'.
Re: adding to hashes
by McDarren (Abbot) on Jul 24, 2006 at 16:50 UTC
    my %C = (%A, %B);

    If you were dealing with hash references, you would do:

    my $C = { %$A, %$B };

    The PDSC is an excellent resource for learning how to grok and manipulate Perl data structures.

    Update: As pointed out below by muba and CountZero, you need to keep in mind that hash keys must be unique, and as such any keys in hash A that also exist in hash B will get clobbered.

    Cheers,
    Darren

Re: adding to hashes
by imp (Priest) on Jul 24, 2006 at 17:02 UTC
    If you are dealing with simple hashes, such as the ones in your post, then the easiest way is as McDarren said.

    If you are dealing with more complicated cases then you need to do a little more work, or use a module such as Hash::Merge to do the work for you.

    For example, if you have the following hash:

    my %a = ( k1 => 1, k2 => { kk3 => 3 }, ); my %b = ( k1 => 5, k2 => { kk4 => 4 }, ); my %c = (%a,%b);
    In the above example a simple merge of the hashes results in the following:
    %c = ( 'k1' => 5 'k2' => { 'kk4' => 4 }, );
    Notice that the deep members of the hash are not merged, only the top level.
Re: adding to hashes
by muba (Priest) on Jul 24, 2006 at 16:56 UTC
    While this is correct, I would like to add that any values that exist in both %A and %B are overwritten by the one in %B. For example:
    my %A = (a => "A", b => "B"); my %B = (b => "A"); my %C = (%A, %B); print "$_ => $C{$_}\n" foreach keys %C;
    Output:
    a => A
    b => A
Re: adding to hashes
by Ieronim (Friar) on Jul 24, 2006 at 17:28 UTC
    if you want to decide how to deal with keys existing in both hashes, use simple foreach:
    foreach my $key (keys %B) { if (exists $A{$key}) { # do something next; } $A{$key} = $B{$key}; }

         s;;Just-me-not-h-Ni-m-P-Ni-lm-I-ar-O-Ni;;tr?IerONim-?HAcker ?d;print
Re: adding to hashes
by CountZero (Bishop) on Jul 24, 2006 at 16:58 UTC
    Of course if the hashes share duplicate keys, probably with different values, the duplicate keys in the second hash will overwrite the duplicate key in the first hash.

    CountZero

    "If you have four groups working on a compiler, you'll get a 4-pass compiler." - Conway's Law