This is what I would definitely use for complex structure, as I would have different rules for certain keys at different depth levels.
As for simple merge, I tend to use the opposite of what GrandFather uses. My target hashes are mostly new initialized ones, and the the source is taken as custom values that override the default. So I just stuff source
into target. Because the source hash is actually a reference, it will be dereferenced.
sub some_meth {
my($self, $source) = @_;
my %target = (
key1 => 'default_1',
key2 => 'default_2',
keyN => 'default_N',
%$source,
);
# do somethings with %target
}
Of course, GrandFather's technique can be applied as well. And I can see an advantage to have a chance to check the source prior to merging.
my %target = (
# initialization
);
%target{keys %$source} = values %$source
if defined $source && ref $source eq 'HASH';
Open source softwares? Share and enjoy. Make profit from them if you can. Yet, share and enjoy!
|