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

Possible duplicate:
What is the best way to make a deep copy of the data structure in Perl?

In my code, I do:

@data_new=@data; 

and then I modify @data .

The problem is that @data_new always changing. It's like @data_new - it's just a reference to what's in @data .

How to make a copy of an array that is not a reference, but a new copy of all values?

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

+8
arrays perl copy
source share
2 answers

The code will copy the contents of the list to the new list. However, if you store links in a list (and you need to create a two-dimensional array in Perl), the links are copied, not the objects that the links point to. Therefore, when you manipulate one of these objects with a link through one list, it seems that the other list changes when in fact both lists contain only the same links.

You will need to make a β€œdeep copy” of the list if you also want to duplicate all the objects referenced. See this question for some ways to achieve this.

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

 @data_new = map { [@$_] } @data; 
+16
source share

See perlfaq4 "How to Print or Copy a Recursive Data Structure." That is, use the dclone method from Storable .

 use Storable qw(dclone); @data_new = @{ dclone(\@data) } 
+27
source share

Source: https://habr.com/ru/post/649951/


All Articles