In Perl, how can I make a deep copy of an array? [duplicate]

三世轮回 提交于 2019-12-10 02:58:16

问题


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

In my code i do:

@data_new=@data;

and then I change @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 is a two dimensional array, by the way.


回答1:


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.

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;



回答2:


See perlfaq4's "How do I print out or copy a recursive data structure". That is, use the dclone method from Storable.

use Storable qw(dclone);
@data_new = @{ dclone(\@data) }


来源:https://stackoverflow.com/questions/4390030/in-perl-how-can-i-make-a-deep-copy-of-an-array

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!