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

#!/usr/local/bin/perl
use warnings;
use strict;
my %h1 = (a => 'b');
my %h2 = (a => 'b');
my $hr1 = \%h1;
my $hr2 = {%h2};
$hr1->{a} = 'c';
$hr2->{a} = 'c';
print "$h1{a} $h2{a}\n";

Download it here.

The output looks like this:

c b


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