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
2009-08-06 23:26:07
Why doesn't %a = (%a, %b); work?%a gets "erased"
biznez
2009-08-06 23:31:42
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
2009-08-06 23:51:14
@yskhoo: it does work.
ysth
2009-08-07 02:48:09
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
2009-08-07 10:51:48
In which case they should look at Hash::Merge on the CPAN
MkV
2009-08-07 10:53:16
+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
2009-08-06 23:42:14
For extra credit, with a hash ref in a and b, we do @{$a}{keys %$b} = values %$b;
daotoad
2009-08-07 05:30:30
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
2009-08-10 20:04:28
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
2009-08-10 20:49:46
@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
2009-08-10 21:01:58