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.
In reply to Re: Global variable unexpectedly modified when passed by reference
by GotToBTru
in thread Global variable unexpectedly modified when passed by reference
by fshrewsb
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |