在Perl中,我怎样才能使一个数组的深层副本? [英] In Perl, how can I make a deep copy of an array?

查看:119
本文介绍了在Perl中,我怎样才能使一个数组的深层副本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:结果
  <一href=\"http://stackoverflow.com/questions/388187/whats-the-best-way-to-make-a-deep-copy-of-a-data-structure-in-perl\">What's最好的方法,使数据结构的深层副本在Perl?

在我的code我做的:

In my code i do:

@data_new=@data;

然后我换 @data

问题是, @data_new 总是变化为好。
这就像 @data_new 只是在什么 @data 引用。

The problem is that @data_new always changes as well. It's like @data_new is just a reference to what's in @data.

如何使一个数组的一个副本这不是一个参考,但所有值的新副本?

How do i make a copy of an array which is not a reference but a new copy of all the values?

@data 是一个二维数组,顺便说一句。

@data is a two dimensional array, by the way.

推荐答案

在code你的列表的内容复制到一个新的列表。但是,如果在列表中存储引用(你以创造在Perl二维数组必须的),在引用的被复制,而不是对象引用指向。所以,当你操纵这些引用的对象之一,通过一个列表,它看起来好像其他列表正在发生变化,而实际上这两个列表中只包含相同的引用。

The code you have will copy the contents of the list to a new list. However, if you are storing references in the list (and you have to in order to create a two-dimensional array in Perl), the references are copied, not the objects the references point to. So when you manipulate one of these referenced objects through one list, it appears as though the other list is changing, when in fact both lists just contain identical references.

您将不得不列表的深层复制,如果您想复制所有引用的对象了。见<一href=\"http://stackoverflow.com/questions/388187/whats-the-best-way-to-make-a-deep-copy-of-a-data-structure-in-perl\">this问题一些方法来做到这一点。

You will have to make a "deep copy" of the list if you want to duplicate all referenced objects too. See this question for some ways to accomplish this.

鉴于你的二维数组的情况下,这应该工作:

Given your case of a two-dimensional array, this should work:

@data_new = map { [@$_] } @data;

这篇关于在Perl中,我怎样才能使一个数组的深层副本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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