#!/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.
In reply to Re^2: update a hash with a hash
by beable
in thread update a hash with a hash
by stupidius
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |