Perl hashref/property confusion

113 views Asked by At

Ignoring the fact that this probably wouldn't happen if one was using strict and warnings, I'd like to know why these two cases differ.

#!/usr/local/perl5/bin/perl

$x[0] = "";
$y[0] = "";

$x[0]->{name} = "SRV";
$y[0]->{name} = "FINAL";
print "$x[0]->{name}, $y[0]->{name}\n";

$x[1]->{name} = "SRV";
$y[1]->{name} = "FINAL";
print "$x[1]->{name}, $y[1]->{name}\n";

Output is:

FINAL, FINAL
SRV, FINAL

Why, when the index is zero, does the y[0]->{name} assignment affect x[0]->{name}, but not when the index is one?

Thanks,

Sean.

1

There are 1 answers

2
ikegami On

That's not the code you actually ran. In the code you presented, $x[0] and $y[0] are references to different hashes, but in the problematic code, $x[0] and $y[0] are references to the same hash. Like in the following code:

my %hash = { name => "SRV" };
$x[0] = \%hash;           # $x[0] is a reference to %hash.
$y[0] = $x[0];            # $y[0] is a reference to %hash.
$y[0]->{name} = "FINAL";  # Changes $hash{name}.

print $x[0]->{name};      # Prints $hash{name}.
print $y[0]->{name};      # Prints $hash{name}.

The above problem can be fixed by changing

$y[0] = $x[0];

to

$y[0] = { %{ $x[0] } };

or

use Storable qw( dclone );
$y[0] = dclone( $x[0] );