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.
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.
No, it does not. When you assign a new object to the "original" array, this does not affect the copy.
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.
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) }
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With