in reply to Modify hash reference itself

I see that your question has been answered. I just want to point out that the %$a = { %$a,  %$b }; part makes a copy of %$a and %$b before the assignment, which could be less efficient when the hash sizes are big. The following code works off the reference to %hash directly without making an additional copy of itself.
use strict; use Data::Dumper; my %hash1 = qw/ A 1 B 2 /; my %hash2 = qw/ C 3 D 4 /; mergetwohashes(\%hash1, \%hash2); print Dumper(\%hash1); sub mergetwohashes { my ($a, $b) = @_; $a->{$_} = $b->{$_} foreach keys %$b; }
And the output is as expected -
$VAR1 = { 'A' => '1', 'B' => '2', 'C' => '3', 'D' => '4' };

Replies are listed 'Best First'.
Re: Re: Modify hash reference itself
by Anonymous Monk on Dec 02, 2003 at 00:55 UTC
    Yes thank you, and thanks to all, I'm shocked at the quantity, quality, and speed of the responses here.

    Yea, the reason I used the {%{$a}, %{$b} } example was both because it looks simpler, and because it conveys my question (actually if I had used your example I wouldn't have had this question because you're not replacing the hash ref, you're adding/changing keys within it).

    In other words, my code was just demo code, and my real sub is bigger and does more than just merge.

    But while we're on the subject of hash merging, there's also this:

    @b{keys %a} = values %a;
    (given %a and %b)

    And also I have bookmarked a thread from comp.lang.perl.misc from years ago:

    http://tinyurl.com/xaiz

    thanks again everyone

      Ah... I discussed this approach with davido the other day, I thought the benchmarking showed that this was actually slower than my simple approach. Strangely enough. ;-)