in reply to Re: Global variable unexpectedly modified when passed by reference
in thread Global variable unexpectedly modified when passed by reference

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

Replies are listed 'Best First'.
Re^3: Global variable unexpectedly modified when passed by reference
by fshrewsb (Acolyte) on Dec 08, 2014 at 16:00 UTC

    Thanks, de-referencing the passed hashref and operating on that does what I need, as this one-liner demonstrates :

    perl -w -MData::Dumper -e 'use strict; my $hash = {a => 1, b => 2}; sub mysub{my $h = shift; my %dh = %$h; delete $dh{"b"}}; mysub($hash); print Dumper($hash)'