Pitonyak::DeepCopy - Copy an object reference with new copies, even if it contains references.


use Pitonyak::DeepCopy; my $new_hash_ref = Pitonyak::DeepCopy::deep_copy(\%original_hash);


Assume the hash A% contains a hash. Now, copy the elements from A% into B%.

The obvious solution enumerates the keys and assigns the value from A% to B%. Something like this:

foreach (keys A%) $B{$_} = $A{$_};

Unfortunately, the contained hash is a reference, %A and %B both reference the same hash. In other words, if you modify the contained hash in %A or %B, you change it in both.

The proper solution is obtained using

my $hash_ref = Pitonyak::DeepCopy::deep_copy(\%A);


Copyright 1998-2009, Andrew Pitonyak

This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself.

Modification History

September 01, 2002

Version 1.00 First release

September 10, 2002

Version 1.01 Changed internal documentation to POD documentation. Added parameter checking.

January 18, 2007

Version 1.02 Updated POD and reformatted.

January 18, 2007

Version 1.03 Removed reference to Carp library, because it is not used.




Accept a reference to an object and return a reference to a new copy of the object.

$copy_ref = deep_copy(\%hash_ref);