Re: disjoint copy one hash to another

[email protected] ("Chas. Owens")
Newsgroups perl.beginners
Message-ID <[email protected]>
On Tue, May 27, 2008 at 3:52 AM, Ram Prasad <[email protected]> wrote:
> 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 )
>
> How do I avoid this ?
>
> 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]);
> foreach my $i( 1 .. 5){
>  my %y = %x;
>  push @{$y{a}},5;
>  print "[Loop $i] " . join(" ",@{$x{a}}) ."\n";             # I want
> this to be same in every loop
> }

You need a deep copy.  The dclone* function in Storable is the
recommended method of getting one.  You may also want to go back and
reread perlreftut**, perlref***, and perldsc***.

#!/usrbin/perl

use strict;
use warnings;
use Storable qw<dclone>;

my %x = (
	a => [1, 2]
);
for my $i (1 .. 5) {
	my %y = %{dclone(\%x)};
	push @{$y{a}}, 5;
	print "[Loop $i] @{$x{a}}\n";
}

* perldoc Storable or http://perldoc.perl.org/Storable.html
** perldoc perlreftut or http://perldoc.perl.org/perlreftut.html
*** perldoc perlref or http://perldoc.perl.org/perlref.html
**** perldoc perldsc or http://perldoc.perl.org/perldsc.html
-- 
Chas. Owens
wonkden.net
The most important skill a programmer can have is the ability to read.
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.