A note of caution. Copying by dereference as shown in examples above is shallow copying only. In a nested data structure (e.g., hash-of-hashes, array-of-arrays, etc.), a reference may be present at any level. (Indeed, in Perl, a nested data structure must, by definition, contain one or more references at one or more levels. See perldsc.) Had the hashes used in the examples above contained a hash/array/whatever reference as a value, the problem would potentially have just been moved down one or more levels. A reference remains a reference to the original referent no matter how many times it is simply copied.
c:\@Work\Perl\monks>perl -wMstrict -MData::Dump -le "my @ra = (1, 2, 3); my %hash = ( a => 'ok', b => \@ra, ); ;; S(\%hash); ;; dd \@ra; dd \%hash; ;; sub S { my $hashref = shift; my %hashcopy = %$hashref; ;; return do_something_with(\%hashcopy); } ;; sub do_something_with { my $hashref = shift; ;; $hashref->{b}[0] = 9; $hashref->{b}[1] = 9; $hashref->{b}[2] = 9; return 1; } " [9, 9, 9] { a => "ok", b => [9, 9, 9] }
In reply to Re: Global variable unexpectedly modified when passed by reference
by AnomalousMonk
in thread Global variable unexpectedly modified when passed by reference
by fshrewsb
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |