If you ran your code with use warnings; it would tell you that your
my %h = shift;
in mysub1 is not doing what you think.
$VAR1 = { 'a' => 1 }; Odd number of elements in hash assignment at ./spw1109575_GTBT line 21 +. $VAR1 = { 'b' => 2, 'a' => 1 };
The shift is taking the first element from the @_ array in which the %hash2 hash was passed to the subroutine and assigning that single scalar to the %h hash in the subroutine, hence the "Odd number" warning. You got the correct result from the Dump output anyway because passing by value, even the incorrect one, doesn't affect the original which is what you were illustrating.
What you should have done is assign all of @_ to the hash
use strict; use warnings; 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'}; }
which produces
$VAR1 = { 'a' => 1 }; $VAR1 = { 'a' => 1, 'b' => 2 };
I hope this is of interest.
Cheers,
JohnGG
In reply to Re^2: Global variable unexpectedly modified when passed by reference
by johngg
in thread Global variable unexpectedly modified when passed by reference
by fshrewsb
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |