wanna_code_perl has asked for the wisdom of the Perl Monks concerning the following question:
Hello Monks,
What is the most elegant way to combine two hashes by reference? I basically want to do this:
$x = { foo => "abc" }; $x .= { bar => "def", baz => "ghi" }; # I want $x to be: # { foo => "abc", bar => "def", baz => "ghi" }
Obviously, the concatenation operator won't have the desired effect.
And I know I can manually concatenate the two hashes, with, say:
my $temp = { bar => "def", baz => "ghi" }; foreach my $key (keys %$temp) { $x->{$key} = $temp->{$key}; }
Overwriting values is expected and OK in my application.
However, is there a more elegant (and time/memory efficient) solution?
The hash refs are a return from a function. I want to concatenate the return from successive calls.
Update: Thanks for the good ideas! It turns out it is cleaner for me to just pass the reference to my helper functions, and let them modify it. I was trying to avoid the extra parameter, but looks like that will be the easiest to maintain in this case.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Concatenate anonymous hash ref
by Corion (Patriarch) on Oct 14, 2008 at 16:49 UTC | |
|
Re: Concatenate anonymous hash ref
by ikegami (Patriarch) on Oct 14, 2008 at 17:25 UTC | |
by JavaFan (Canon) on Oct 14, 2008 at 19:11 UTC | |
|
Re: Concatenate anonymous hash ref
by Thelonius (Priest) on Oct 14, 2008 at 20:55 UTC |