Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the best way to make a deep copy of a data structure in Perl?

Tags:

clone

perl

People also ask

What is Dclone in Perl?

As the documentation for Storable shows dclone( ... ) is the equivalent of composition of thaw and freeze as thaw( freeze( ... )) . thaw can thaw any type of encoded structure. A reference can refer to anything in Perl. That array of hashes of arrays that you wanted, the hash of hashes of arrays, ....

How do I copy a hash in Perl?

To do a full deep copy, you can use the core module Storable . Thank you; this is precisely what I was looking for. Using Storable qw(clone) worked fine for me in Perl 5.22 in 64-bit Linux. Using Clone qw(clone) causes exactly the same code to crash due to a segfault internal to Perl.

How do I copy an array in Perl?

To copy a Perl array named @array1 to a Perl array named @array2 , just use this syntax: @array2 = @array1; In other languages that seems more like @array2 is a reference to @array1, but in Perl it's a copy. As you can see, the contents of the two Perl arrays following the copy operation are different.


Clone is much faster than Storable::dclone, but the latter supports more data types.

Clone::Fast and Clone::More are pretty much equivalent if memory serves me right, but less feature complete than even Clone, and Scalar::Util::Clone supports even less but IIRC is the fastest of them all for some structures.

With respect to readability these should all work the same, they are virtually interchangeable.

If you have no specific performance needs I would just use Storable's dclone.

I wouldn't use Data::Dumper for this simply because it's so cumbersome and roundabout. It's probably going to be very slow too.

For what it's worth, if you ever want customizable cloning then Data::Visitor provides hooking capabilities and fairly feature complete deep cloning is the default behavior.


My impression is that Storable::dclone() is somewhat canonical.


Clone is probably what you want for that. At least, that's what all the code I've seen uses.