http://qs321.pair.com?node_id=228543

BrowserUk has asked for the wisdom of the Perl Monks concerning the following question:

I'm writing a recursive routine that does destructive processing on a passed ref to an AoHoA... but as I return from each level of recursion, I need to 'undo' the changes made.

Basically, I need to provide a deepcopy of (or some subtree of) the structure as I recurse in so that I retain an unchanged copy as I come back up the tree.

I did a search on CPAN for DeepCopy and came up empty apart from Data:Dumper which of course does a somewhat different thing.

The best I've come up with is:

sub deepcopy{ return $_[0] unless ref $_[0]; return [ map{ deepcopy($_) } @{$_[0]} ] if ref $_[0] eq 'ARRAY' +; return { map{ deepcopy($_) } %{$_[0]} } if ref $_[0] eq 'HASH'; return $_[0]; }

but I far from convinced that this hasn't been written before; or that this isn't full of wholes.

Note: I know it doesn't handle coderefs but that doesn't figure in this particular application.

Is there something better?


Examine what is said, not who speaks.

The 7th Rule of perl club is -- pearl clubs are easily damaged. Use a diamond club instead.