in reply to How to preserve values outside a sub
If you want to pass a local copy, specify that:
pass1({ params => {%$hashref} }); # {%$hashref} makes a copy of the hash '$hashref'
# points to and creates a new ref to it.
You need to "copy" the reference in order to break the link:
my $params = { %{ $self->{params} } };
There's a pitfall here. Be aware that the "copy" above is only a shallow copy. Any references nested within the referent of the reference being shallow-copied still allow complete read/write access to their referents.
Bottom line: references be tricky. (Update: See perlref, perlreftut, maybe also perldsc.)c:\@Work\Perl\monks>perl -wMstrict -MData::Dump -le "my $hashref = { foo => { bar => 'nice' } }; dd 'before pass1: ', $hashref; ;; pass1({ params => { %$hashref } }); ;; dd 'after pass1: ', $hashref; ;; ;; sub pass1 { my $self = shift; my $params = $self->{params}; dd 'in pass1, before assignments ', $params; ;; $params->{fizz} = 'fazz'; $params->{foo}{bar} = 'KaPow'; dd 'in pass1 after assignments ', $params; } " ("before pass1: ", { foo => { bar => "nice" } }) ("in pass1, before assignments ", { foo => { bar => "nice" } }) ( "in pass1 after assignments ", { fizz => "fazz", foo => { bar => "KaPow" } }, ) ("after pass1: ", { foo => { bar => "KaPow" } })
Give a man a fish: <%-{-{-{-<
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: How to preserve values outside a sub
by Theodore (Hermit) on Oct 26, 2017 at 11:55 UTC |