in reply to merging two hashes and updating the 1st hash keys.

sathiya.sw:

I think this is what you want:

# cat 791596.pl use strict; use warnings; use Data::Dumper; my %h1 = ( e=>'f', c=>'d', a=>'b' ); my %h2 = ( e=>'K', a=>'J', q=>'V' ); do { my @b = grep {exists $h1{$_}} keys %h2; @h1{@b} = @h2{@b}; }; print Dumper(\%h1); # perl 791596.pl $VAR1 = { 'e' => 'K', 'c' => 'd', 'a' => 'J' };

The first hash is updated with the values from the second, but no new keys (such as q in the second hash) are added to the first hash.

...roboticus

Update: Correction as per Gramps' reply. ;^)

Replies are listed 'Best First'.
Re^2: merging two hashes and updating the 1st hash keys.
by GrandFather (Saint) on Aug 27, 2009 at 20:52 UTC

    Use of exists in the grep, not defined may be clearer. defined implies that there is an element in %h1 that matches the key, but that it may be undef. exists tests for the existence of the element with no implication that it should already be there or that it may be set to any particular value.

    It's interesting to note though that defined doesn't cause elements in %h1 to be autovified as might be expected.


    True laziness is hard work