http://qs1969.pair.com?node_id=60526

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