Beefy Boxes and Bandwidth Generously Provided by pair Networks
P is for Practical


by Caillte (Friar)
on Feb 23, 2001 at 22:51 UTC ( #60526=snippet: 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?

What's my password?
Create A New User
Node Status?
node history
Node Type: snippet [id://60526]
[RonW]: My daughter and I like to "fly" Flightgear. What ever aircraft we pick, she usually shoots me out of the sky
[Corion]: Oooh. I didn't know about Flightgear. I've been looking at maybe playing with a flight simulator again, thanks!

How do I use this? | Other CB clients
Other Users?
Others meditating upon the Monastery: (10)
As of 2017-02-27 18:14 GMT
Find Nodes?
    Voting Booth?
    Before electricity was invented, what was the Electric Eel called?

    Results (390 votes). Check out past polls.