Beefy Boxes and Bandwidth Generously Provided by pair Networks
Do you know where your variables are?
 
PerlMonks  

deepcopy

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

Description:

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;
}

Comment on deepcopy
Download 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 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: deepcopy
by merlyn (Sage) on Feb 24, 2001 at 12:49 UTC

Back to Snippets Section

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others chanting in the Monastery: (13)
As of 2014-12-21 08:30 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    Is guessing a good strategy for surviving in the IT business?





    Results (104 votes), past polls