Merging two hashrefs in Perl

I came across an interesting and very simple way to merge the contents of two hashrefs today. A hash is made up of pairs – a key and a corresponding value. As an example, the following can be pasted into a shell session on most machines that have perl installed.
perl -MData::Dumper -le ‘
$x = { a => 1, b => 2 };
$y = { c => 3, d => 4 };
$x = { %$x, %$y };
print Dumper($x);

If all goes well, you should see that all 4 keys (a,b,c,d) are in the resulting hashref together with the correct values (1,2,3,4). Because of the way hashes work in Perl, they almost certainly won’t be in the same order.
The values in $y seem to override any existing values in $x so if $y is changed to be { a => 3, d => 4 }, the output will be { a => 3, b => 2, d => 4 }

Published by


You can also find me on Google+, Twitter and Facebook.