Prev: help with perl search/replace regex
Next: FAQ 7.27 How can I comment out a large block of Perl code?
From: PerlFAQ Server on 22 Jan 2010 18:00 This is an excerpt from the latest version perlfaq4.pod, which comes with the standard Perl distribution. These postings aim to reduce the number of repeated questions as well as allow the community to review and update the answers. The latest version of the complete perlfaq is at http://faq.perl.org . -------------------------------------------------------------------- 4.56: How do I merge two hashes? (contributed by brian d foy) Before you decide to merge two hashes, you have to decide what to do if both hashes contain keys that are the same and if you want to leave the original hashes as they were. If you want to preserve the original hashes, copy one hash (%hash1) to a new hash (%new_hash), then add the keys from the other hash (%hash2 to the new hash. Checking that the key already exists in %new_hash gives you a chance to decide what to do with the duplicates: my %new_hash = %hash1; # make a copy; leave %hash1 alone foreach my $key2 ( keys %hash2 ) { if( exists $new_hash{$key2} ) { warn "Key [$key2] is in both hashes!"; # handle the duplicate (perhaps only warning) ... next; } else { $new_hash{$key2} = $hash2{$key2}; } } If you don't want to create a new hash, you can still use this looping technique; just change the %new_hash to %hash1. foreach my $key2 ( keys %hash2 ) { if( exists $hash1{$key2} ) { warn "Key [$key2] is in both hashes!"; # handle the duplicate (perhaps only warning) ... next; } else { $hash1{$key2} = $hash2{$key2}; } } If you don't care that one hash overwrites keys and values from the other, you could just use a hash slice to add one hash to another. In this case, values from %hash2 replace values from %hash1 when they have keys in common: @hash1{ keys %hash2 } = values %hash2; -------------------------------------------------------------------- The perlfaq-workers, a group of volunteers, maintain the perlfaq. They are not necessarily experts in every domain where Perl might show up, so please include as much information as possible and relevant in any corrections. The perlfaq-workers also don't have access to every operating system or platform, so please include relevant details for corrections to examples that do not work on particular platforms. Working code is greatly appreciated. If you'd like to help maintain the perlfaq, see the details in perlfaq.pod. |