Beefy Boxes and Bandwidth Generously Provided by pair Networks
There's more than one way to do things
 
PerlMonks  

deepcopy

by Caillte (Friar)
on Feb 23, 2001 at 22:51 UTC ( [id://60526]=CUFP: print w/replies, xml ) Need Help??

I had to use a complex data structure in a program at work involving hashrefs within arrays within a hash and copying it was a pig because the copied variable contained references to data stored withing the original variable. This led to problems with data corruption and so on. So I came up with deepcopy......

See the difference below. In the first pair %bar contains a pointer to the data contained within %foo but deepcopy seperated the variables.

%foo = ( 'x' => [ { 'a' => 1, 'b' => 2 }, 100 ] ); %bar = ( 'x' => $foo{'x'} ); %bim = ( 'x' => [ { 'a' => 1, 'b' => 2 }, 100 ] ); %bom = ( 'x' => [ { 'a' => 1, 'b' => 2 }, 100 ] );
use Data::Dumper; use Storable qw(freeze thaw); # Set up some complex variables, a hash within an array within a hash my $x = { a => 1, b => 2, }; my %foo = ( x => [$x, 100], ); # Copy it... my %bar = %foo; # Then deepcopy it... my($bim, $bom) = deepcopy(\%foo, \%bar); # Then lets have a look inside each variable... ;) my $dump = Data::Dumper->new([\%foo, \%bar, $bim, $bom], [qw(*foo *bar + *bim *bom)]); print $dump->Dump; # The sub itself sub deepcopy { my @return; # This sub will take any number of references to a variable and # parse them all. The result is put into @result and returned as # an array while(@_) { push @return, thaw freeze shift; } return @return; }

Replies are listed 'Best First'.
Re: deepcopy
by TheoPetersen (Priest) on Feb 23, 2001 at 23:09 UTC
    You'll gain some efficiency by using dclone explicitly instead of thaw(freeze). dclone is implemented at a lower level in Storable's C code.
Re (tilly) 1: deepcopy
by tilly (Archbishop) on Feb 23, 2001 at 23:03 UTC
    You will be bitten if someone calls that in scalar context. You should check wantarray and do something reasonable in scalar context...
Re: deepcopy
by merlyn (Sage) on Feb 24, 2001 at 12:49 UTC

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: CUFP [id://60526]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others sharing their wisdom with the Monastery: (4)
As of 2024-04-24 19:44 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found