in reply to Re: Replace the value of a hash
in thread Replace the value of a hash

#!/usr/bin/perl use Data::Dumper; %hash1 = (a=>1,b=>2,c=>3); %hash2 = (1=>'A',2=>'B'); @hash3{keys %hash1}= @hash2{values %hash1}; #defined $hash3{$_} or delete $hash3{$_} for keys %hash3; print Dumper \%hash3; __END__ $VAR1 = { 'c' => undef, 'a' => 'A', 'b' => 'B' };

I like this technique, but it leaves undef values if hash1 don't fully match the keys of hash2. The commented out line cleans up the undef, but if you have to resort to that whats the point. (I note also that the OP was creating a new hash, while most solutions so far modify the first hash.)

qq

Replies are listed 'Best First'.
Re: Re: Re: Replace the value of a hash
by ambrus (Abbot) on Apr 03, 2004 at 20:31 UTC

    Yes, that's true.

    Then, if you need a solution that will give you

    +{ 'b' => 'B', 'a' => 'A', 'c' => 3 };

    from the above data, the best is probably a straightforward solution like

    while (my ($key, $val)= each %hash1) { exists $hash2{$val} and $hash1{$key}= $hash2{$val}; }

    As this

    { my %thash= (map (($_,$_), values %hash1), %hash2); @hash3{keys %hash1}= @thash{values %hash1}; }

    is not only difficult to read, but also inefficent depending on your data.