在 Perl 中复制 hashref [英] Copying a hashref in Perl

查看:53
本文介绍了在 Perl 中复制 hashref的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

<块引用>

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

我显然对 Perl 中 hashrefs 的工作方式有一些误解,我在这里寻求纠正.

我需要获取一份 hashref 的副本,我可以在不修改原始文件的情况下使用它.根据我的研究,复制 hashref 就像使用等号运算符:

我的 $hashref_copy = $hashref;

但据我所知,所做的只是让 $hashref_copy 成为指向原始对象的指针.考虑一下这个玩具代码:

<预><代码>我的 $hashref = {data => "fish"};我的 $hashref_copy = $hashref;$hashref_copy->{data} = "筹码";打印 "$hashref->{data}\n";

如果 $hashref_copy 真的是一个独立的副本,我希望这段代码打印fish".相反,它会打印筹码".

所以要么1)我误解了某些东西,要么2)Perl坏了.我很确定它不是#2,尽管我的自我会让我这么想.

我哪里出错了?我需要做什么才能修改 $hashref_copy 显示在原始 $hashref 中?

解决方案

当您将 hashref 复制到另一个标量时,您正在复制对同一哈希的引用.这类似于将一个指针复制到另一个指针中,但不会更改任何指向的内存.

您可以轻松创建散列的浅拷贝:

my $copy = { %$source };

列表上下文中的 %$source 位将扩展为键值对列表.花括号(匿名哈希构造函数)然后获取该列表并从中创建一个新的 hashref.如果您的结构是一维的,或者您不需要克隆任何包含的数据结构,那么浅拷贝就可以了.

要进行完整的深拷贝,可以使用核心模块Storable.

use Storable 'dclone';我的 $deep_copy = dclone $source;

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

I'm apparently misunderstanding something about how hashrefs work in Perl, and am here looking to correct that.

I need to get a copy of a hashref that I can fiddle with without modifying the original. According to my research, copying a hashref is just as simple as using the equals operator:

my $hashref_copy = $hashref;

But as far as I can tell, all that does is make $hashref_copy a pointer to the original object. Consider this toy bit of code:


my $hashref = {data => "fish"};

my $hashref_copy = $hashref;
$hashref_copy->{data} = "chips";

print "$hashref->{data}\n";

If $hashref_copy were really an independent copy, I'd expect this code to print "fish". Instead, it prints "chips".

So either 1) I'm misunderstanding something or 2) Perl is broken. I'm quite certain it isn't #2, in spite of what my ego would have me think.

Where am I going wrong? And what do I need to do to make modifications to $hashref_copy not show up in the original $hashref?

解决方案

When you copy a hashref into another scalar, you are copying a reference to the same hash. This is similar to copying one pointer into another, but not changing any of the pointed-to memory.

You can create a shallow copy of a hash easily:

my $copy = { %$source };

The %$source bit in list context will expand to the list of key value pairs. The curly braces (the anonymous hash constructor) then takes that list an creates a new hashref out of it. A shallow copy is fine if your structure is 1-dimensional, or if you do not need to clone any of the contained data structures.

To do a full deep copy, you can use the core module Storable.

use Storable 'dclone';

my $deep_copy = dclone $source;

这篇关于在 Perl 中复制 hashref的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆