The stupid question is the question not asked | |
PerlMonks |
Re: Readonly references, replicating data structuresby haukex (Archbishop) |
on Jan 22, 2017 at 12:20 UTC ( [id://1180116]=note: print w/replies, xml ) | Need Help?? |
Hi nikmit, I expected the below code to create a fresh copy of @arr every time gimme() is executed. In the code you showed, @arr is only initialized once, so the anonymous hashes are only created once. The first and only element of @arr is a reference to an anonymous hash. When you say my @result = @arr;, the elements of @arr are copied into @result, so that reference is copied exactly, so it still points to the same anonymous hash. This is known as a "shallow copy" and is how arrays and hashes are copied in Perl. (Note: Making @arr Readonly won't change that.) To get a "deep copy" or "clone", choroba already pointed you to Storable and Clone, but there's another solution:
This causes the array and the anonymous hashes to be re-created on every call to gimme. Hope this helps, Update: Minor clarifications to wording.
In Section
Seekers of Perl Wisdom
|
|