tags:

views:

1242

answers:

2

How do I append hash a to hash b in Perl without using a loop?

+12  A: 

If you mean take the union of their data, just do:

%c = (%a, %b);
bdonlan
Why doesn't %a = (%a, %b); work?%a gets "erased"
biznez
It works for me: "%a=('a' => 'b', 'c' => 1); %b=('c' => 'd'); %a = (%a, %b); print join(', ', map { "'$_' => \"${a{$_}}\"" } keys %a), "\n";" Items from %b with the same key take precedence, but other items from %a are present after the union.
outis
@yskhoo: it does work.
ysth
that might be the OP's problem, they might want to merge the values of the hash, so $a{'c'} ends up being [1, 'd']
MkV
In which case they should look at Hash::Merge on the CPAN
MkV
+11  A: 

You can also use slices to merge one hash into another:

@a{keys %b} = values %b;

Note that items in %b will overwrite items in %a that have the same key.

outis
For extra credit, with a hash ref in a and b, we do @{$a}{keys %$b} = values %$b;
daotoad
I expect this to be more efficient than the other reply, because that one recreates the hash also for the already existing items, while this one just adds keys for the new items. If there were many items in %a, compared to %b, the difference can be respectable.
bart
Maybe. My approach also walks %b twice. If %b is larger than %a, the other technique might be faster. Fastest of all might be a loop, but the OP didn't want that.
outis
@bart: looks like you were right. Some rather simple timing tests for perl 5.8.9 on OS X 10.4 place the slice approach about 2.4 times faster, even with %b much larger than %a. Your mileage may vary.
outis