简体   繁体   中英

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

Given a data structure (eg a hash of hashes), what's the clean/recommended way to make a deep copy for immediate use? Assume reasonable cases, where the data's not particularly large, no complicated cycles exist, and readability/maintainability/etc. are more important than speed at all costs.

I know that I can use Storable , Clone , Clone::More, Clone::Fast , Data::Dumper , etc. What's the current best practice?

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.

我的印象是Storable::dclone()有点规范。

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

Quick and dirty hack if you're already dealing with JSONs and using the JSON module in your code: convert the structure to a JSON and then convert the JSON back to a structure:

use JSON;

my %hash = (
    obj => {},
    arr => []
);

my $hash_ref_to_hash_copy = from_json(to_json(\%hash));

The only negative possibly being having to deal with a hash reference instead of a pure hash, but still, this has come in handy a few times for me.

尝试使用Panda :: Lib中的 fclone ,这似乎是最快的(用XS编写)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM