in reply to update a hash with a hash

hi the following code must work as far as i understood the question. I assumed that the 2 keys for which values have to be changed are the same as keys in the second hash:
#!/usr/bin/perl my %hash1 = ( key1 => val1, key2 => val2, key3 => val3, key4 => val4, key5 => val5); my %hash2 = ( key1 => xxxval1, key2 => xxxval2); out:foreach my $key (keys %hash1) { foreach my $inkey (keys %hash2) { if($key eq $inkey) { $hash1{$key} = $hash2{$inkey}; next out; } } }
hope it solves your problem.

janitored by ybiC: Balanced <code> tags around codeblock

Replies are listed 'Best First'.
Re^2: update a hash with a hash
by beable (Friar) on Jul 15, 2004 at 10:11 UTC
    You should really use <code> </code> tags around your code. It'll look a lot better, like this:
    #!/usr/bin/perl use strict; use warnings; use Data::Dumper; my %hash1 = ( key1 => "val1", key2 => "val2", key3 => "val3", key4 => "val4", key5 => "val5"); my %hash2 = ( key1 => "xxxval1", key2 => "xxxval2"); print Dumper(%hash1), "\n"; out:foreach my $key (keys %hash1) { foreach my $inkey (keys %hash2) { if($key eq $inkey) { $hash1{$key} = $hash2{$inkey}; next out; } } } print Dumper %hash1; __END__

    However, I put it to you that the nested foreach loops are unnecessary, and that this does the same thing:

    #!/usr/bin/perl use strict; use warnings; use Data::Dumper; my %hash1 = ( key1 => "val1", key2 => "val2", key3 => "val3", key4 => "val4", key5 => "val5"); my %hash2 = ( key1 => "xxxval1", key2 => "xxxval2"); print Dumper(%hash1), "\n"; foreach my $inkey (keys %hash2) { if(exists $hash1{$inkey}) { $hash1{$inkey} = $hash2{$inkey}; } } print Dumper %hash1; __END__

    Because hey! It's a hash! There's no need to loop over the keys to see what's in it.