Use Clone.

http://search.cpan.org/author/RDF/Clone-0.13/Clone.pm

use Clone qw(clone);
my $newhash = clone($hashref);


Rob


-----Original Message-----
From: [EMAIL PROTECTED] [mailto:[EMAIL PROTECTED]
Sent: Tuesday, July 29, 2003 5:29 PM
To: [EMAIL PROTECTED]
Subject: Deep Copy


I am trying to make a deep copy in a complex data structure. I have a hash
that has all of its values as anonymous arrays. I need to copy the entire
hash as a completely separate hash so that I can manipulate the data in the
copy without affecting the original data. Copying the key of the hash is
easy, that is plain data. However copying the value is harder because it is
the anonymous array (so whenever I try to copy the data, it always copies
the reference to the array).

-----------------------------------------
my $hashref;

sub hashref()
{
  return $hashref; 
}

$hashref->{ele1} = ["val1", "val2"];
$hashref->{ele2} = ["val3", "val4"];
$hashref->{ele3} = ["val5", "val6"];

my %newhash = %$hashref;

my @keys = keys(%newhash);
foreach my $arraykey (@keys)
{
    my $ref = $hashref->{$arraykey};
    $newhash{$arraykey} = @$ref;
}
---------------------------------------------------

But then when I do: 

--------------------------------------------------
$newhash{ele1}->[0]="x";
$newhash{ele2}->[0]="y";

print $hashref->{ele1}->[0];
print $hashref->{ele2}->[0];
------------------------------------------------

It changes the values in both the referenced hash and the copied hash. How
do I get a real copy?

TIA

Brian Seel

-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]

-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]

Reply via email to