|
Posted by Jens Thoms Toerring on May 27, 2008, 6:27 am
Please log in for more thread options
> When I create a copy of a hash array, the operation on the copy hash
> seems to affect the original hash
> ( when the values are reference elements )
> In the following script %y is a copy hash , but change that and the %x
> original hash is affected
> --------------
> #!/usr/bin/perl
> use strict;
> use warnings;
> my %x = ( a => [1]);
So $x is an array reference, not an array. So $x is
a pointer to an array that's stored somewhere in memory.
> foreach my $i( 1 .. 5){
> my %y = %x;
Here this copy copies the reference, so $x and $y now
point to the same array. The copy operation isn't a "deep
copy" that instead of copying the reference copies what it
points to. A "deep copy" would result in a comparison like
$x == $y
to fail (unless you also change the meaning of the '=='
operator etc. if applied to references) which could get a
bit surprising...
> push @},5;
And here you change the array that both $x and $y point
to.
> How do I avoid this ?
To get around that you will have to create a new array which
$y pointis to and copy the elements of the array $x
points to. So use not just
my %y = %x;
but add
$y = [ @} ];
before you start to change $y.
Regards, Jens
--
\ Jens Thoms Toerring ___ jt@toerring.de
\__________________________ http://toerring.de
|