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

arrays, copy, perl

Solution

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;

Problem

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.

Original source

Related problems