Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

arrays

copy

perl

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.

like image 342
john-jones Avatar asked Dec 08 '10 16:12

john-jones


People also ask

How do I copy an array in Perl?

To copy a Perl array named @array1 to a Perl array named @array2 , just use this syntax: @array2 = @array1; In other languages that seems more like @array2 is a reference to @array1, but in Perl it's a copy. As you can see, the contents of the two Perl arrays following the copy operation are different.

Is arrays copy of a deep copy?

No, it does not. When you assign a new object to the "original" array, this does not affect the copy.

What is a deep copy of an array?

A deep copy of an object is a copy whose properties do not share the same references (point to the same underlying values) as those of the source object from which the copy was made.


2 Answers

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) }
like image 168
Emil Sit Avatar answered Oct 01 '22 15:10

Emil Sit


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;
like image 41
cdhowie Avatar answered Oct 01 '22 15:10

cdhowie