Beefy Boxes and Bandwidth Generously Provided by pair Networks
The stupid question is the question not asked
 
PerlMonks  

Re: Readonly references, replicating data structures

by haukex (Archbishop)
on Jan 22, 2017 at 12:20 UTC ( [id://1180116]=note: print w/replies, xml ) Need Help??


in reply to Readonly references, replicating data structures

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:

sub gimme { my @result = ( { box => { attr => 'foo' }, } ); return \@result; }

This causes the array and the anonymous hashes to be re-created on every call to gimme.

Hope this helps,
-- Hauke D

Update: Minor clarifications to wording.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://1180116]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others admiring the Monastery: (4)
As of 2024-04-20 00:37 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found