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?

In reply to Sending a hash reference to a subroutine, and retain its values after returning from that subroutine by estreb

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.