in reply to Global variable unexpectedly modified when passed by reference
The usual reason to pass a variable by reference is to allow changes in the subroutine! Pass by reference means the subroutine accesses the very same memory location as the main program. If you want the variable to remain intact, pass it by value.
use Data::Dumper; my %hash = (a => 1, b => 2); mysub(\%hash); print Dumper(\%hash); my %hash2 = (a => 1, b => 2); mysub1(%hash2); print Dumper(\%hash2); sub mysub{ my $h = shift; delete $h->{'b'}; } sub mysub1{ my %h = @_; delete $h{'b'}; }
$VAR1 = { 'a' => 1 }; $VAR1 = { 'a' => 1, 'b' => 2 };
Updated to include code example. Updated again to fix error.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Global variable unexpectedly modified when passed by reference
by johngg (Canon) on Dec 08, 2014 at 15:07 UTC | |
by fshrewsb (Acolyte) on Dec 08, 2014 at 16:00 UTC | |
|
Re^2: Global variable unexpectedly modified when passed by reference
by fshrewsb (Acolyte) on Dec 08, 2014 at 14:59 UTC | |
by parv (Parson) on Dec 08, 2014 at 15:27 UTC | |
by GotToBTru (Prior) on Dec 08, 2014 at 15:15 UTC | |
by Anonymous Monk on Dec 08, 2014 at 15:29 UTC |