nikmit has asked for the wisdom of the Perl Monks concerning the following question:
When I initially hit this it seemed incomprehensible... then I figured out why it's happening but not yet how to fix it - so here I am humbly asking for your wisdom.
I expected the below code to create a fresh copy of @arr every time gimme() is executed. Instead it creates a new reference for @arr but reuses all of the nested references. The result is that gimme() returns the last box with its content, rather than a fresh empty box which is what I want...
I considered using Readonly or a configuration file on disk to ensure I get an empty box every time, but both seem clunky and slow. The actual data structure is nested to 5-6 levels and while it is not huge, it will be executed often.
I suspect turning the data structure into an object may be the right path, but I'm yet to pick that side of perl up... What would be your advice?
#!/usr/bin/perl -w use strict; use Data::Dumper; BEGIN { my @arr = ( { box => { attr => { this => 'that', foo => 'bar', }, content => {}, }, }, ); sub gimme { my @result = @arr; return \@result; } } my $box1_ref = gimme(); $box1_ref->[0]->{white_box}->{content}->{apples} = 5; print "tracing: $box1_ref -> $box1_ref->[0] -> $box1_ref->[0]->{white_ +box} -> $box1_ref->[0]->{white_box}->{content}\n"; print Dumper $box1_ref->[0]->{white_box}->{content}; my $box2_ref = gimme(); print "tracing: $box2_ref -> $box2_ref->[0] -> $box2_ref->[0]->{white_ +box} -> $box2_ref->[0]->{white_box}->{content}\n"; print Dumper $box2_ref->[0]->{white_box}->{content};
Result of that code is:
tracing: ARRAY(0x20d9e70) -> HASH(0x1fcf638) -> HASH(0x20d9db0) -> HAS +H(0x20d9de0) $VAR1 = { 'apples' => 5 }; tracing: ARRAY(0x1fab0f0) -> HASH(0x1fcf638) -> HASH(0x20d9db0) -> HAS +H(0x20d9de0) $VAR1 = { 'apples' => 5 };
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Readonly references, replicating data structures
by haukex (Archbishop) on Jan 22, 2017 at 12:20 UTC | |
|
Re: Readonly references, replicating data structures
by choroba (Cardinal) on Jan 22, 2017 at 12:00 UTC | |
|
Re: Readonly references, replicating data structures
by kcott (Archbishop) on Jan 23, 2017 at 00:47 UTC |