Hash reference and hash copy in Perl

The following program illustrates the difference between a hash reference using \%h1 and a hash copy using {%h2}. If we take a reference to the hash using the backslash, \, then modifying the reference also modifies the contents of %h1. If we copy %h2 using { }, modifying the hash reference $hr2 does nothing to %h2

use warnings;
use strict;
# Both %h1 and %h2 are hashes with one entry, with key "a" and value
# "b".
my %h1 = (a => 'b');
my %h2 = (a => 'b');
# $hr1 is a hash reference to %h1.
my $hr1 = \%h1;
# $hr2 is a hash reference to a copy of %h2.
my $hr2 = {%h2};
# Now change the value at key "a" in both $hr1 and $hr2.
$hr1->{a} = 'c';
$hr2->{a} = 'c';
# Here the backslash before the dollar makes it a printing character.
print "Hash which was referenced: \$h1{a} = $h1{a}\n";
print "Hash which was copied: \$h2{a} = $h2{a}\n";

Download it here.

The output looks like this:

Hash which was referenced: $h1{a} = c
Hash which was copied: $h2{a} = b

Copyright © Ben Bullock 2009-2014. All rights reserved. For comments, questions, and corrections, please email Ben Bullock (ben.bullock@lemoda.net). / Privacy / Disclaimer