estreb has asked for the wisdom of the Perl Monks concerning the following question:

Hello Monks, I am trying to create a hash, pass that hash as an argument to a subroutine, and then after returning from that subroutine, keep any of the changes that might have been made by that hash. Here is my code:
#!/usr/bin/perl use strict; use warnings; use Data::Dumper; my %records = (); my $ref = \%records; print "Before call to DoStuff\n"; print "Hash reference: '$ref'\n"; print Dumper(\%records); DoStuff(\%records); print "Back from call to DoStuff\n"; print Dumper(\%records); exit(0); sub DoStuff { my $hash_ref = shift; print("In DoStuff: "); print "Hash reference: '$hash_ref'\n"; my %temp_records = %{ $hash_ref }; $temp_records{"foo"} = "bar"; print Dumper(\%temp_records); return; }
And here is the output:
Before call to DoStuff Hash reference: 'HASH(0x1da6e78)' $VAR1 = {}; In DoStuff: Hash reference: 'HASH(0x1da6e78)' $VAR1 = { 'foo' => 'bar' }; Back from call to DoStuff $VAR1 = {};
After the call to DoStuff(), why is the "foo" key gone? How do I fix this?
  • Comment on Sending a hash reference to a subroutine, and retain its values after returning from that subroutine
  • Select or Download Code

Replies are listed 'Best First'.
Re: Sending a hash reference to a subroutine, and retain its values after returning from that subroutine
by Anonymous Monk on Dec 19, 2014 at 16:00 UTC

    You're making the changes to a (shallow) copy of $hash_ref, %temp_records, which gets discarded when the subroutine ends. Just make the changes directly to $hash_ref, e.g. $hash_ref->{"foo"} = "bar";. See perlreftut and perlref for more information on using references.

Re: Sending a hash reference to a subroutine, and retain its values after returning from that subroutine
by builat (Monk) on Dec 21, 2014 at 04:30 UTC
    my $tmp=DoStuff(\%records); %records=%{$tmp};

      This won't work - DoStuff never returns anything.

      1 Peter 4:10