简体   繁体   English

在 Perl 中制作数据结构的深层副本的最佳方法是什么?

[英]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?我知道我可以使用StorableClone 、 Clone::More、 Clone::FastData::Dumper等。当前的最佳实践是什么?

Clone is much faster than Storable::dclone , but the latter supports more data types. CloneStorable::dclone ,但后者支持更多数据类型。

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. Clone::FastClone::More如果内存对我来说是正确的,那么几乎相当,但是功能甚至比克隆更少,而Scalar::Util::Clone支持甚至更少,但对于某些结构来说,IIRC是最快的。

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. 如果您没有特定的性能需求,我会使用Storable的dclone。

I wouldn't use Data::Dumper for this simply because it's so cumbersome and roundabout. 我不会因为它如此繁琐和迂回而使用Data::Dumper 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. 对于它的价值,如果你想要可定制的克隆,那么Data::Visitor提供了挂钩功能,相当完整的功能完全深度克隆是默认行为。

我的印象是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:如果您已经在处理 JSON 并在代码中使用 JSON 模块,那么快速而肮脏的 hack:将结构转换为 JSON,然后将 JSON 转换回结构:

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编写)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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