Beefy Boxes and Bandwidth Generously Provided by pair Networks
Don't ask to ask, just ask
 
PerlMonks  

comment on

( [id://3333]=superdoc: print w/replies, xml ) Need Help??
The first 2 posts are completely on target, re: reference counting.

As a demo, I re-wrote your a1 sub and added an a2 sub.

Rather than assigning the hash reference in the subroutine to the "global" variable, I would recommend returning the hash reference from the sub as shown in recoded sub a1.

Like in C, it is possible to pass a "pointer", the hash reference to a sub as shown in sub a2. The memory previously used by sub a1 is "re-used", same struct is modified. If "my $href" goes out of lexical scope, its memory will be recovered and reused by Perl.

#!/usr/bin/perl use strict; use warnings; use Data::Dumper; # a cool core module # that dumps any structure my $href = a1(); #hash reference returned from sub print "v1=$href->{'v1'}\n"; #dot operator not needed print Dumper $href; a2($href); print Dumper $href; exit(0); sub a1 { my %hash; $hash{v1} = 10; $hash{v2} = 20; return \%hash; # %hash memory will "live" due to # reference counting } sub a2 { my ($href) = @_; $href -> {v1} = 30; #quotes are ok but not needed $href -> {'v2'} = 40; return; } __END__ v1=10 $VAR1 = { 'v2' => 20, 'v1' => 10 }; $VAR1 = { 'v2' => 40, 'v1' => 30 };

In reply to Re: Do subroutine variables get destroyed? by Marshall
in thread Do subroutine variables get destroyed? by bt101

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



  • Are you posting in the right place? Check out Where do I post X? to know for sure.
  • Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
    <code> <a> <b> <big> <blockquote> <br /> <dd> <dl> <dt> <em> <font> <h1> <h2> <h3> <h4> <h5> <h6> <hr /> <i> <li> <nbsp> <ol> <p> <small> <strike> <strong> <sub> <sup> <table> <td> <th> <tr> <tt> <u> <ul>
  • Snippets of code should be wrapped in <code> tags not <pre> tags. In fact, <pre> tags should generally be avoided. If they must be used, extreme care should be taken to ensure that their contents do not have long lines (<70 chars), in order to prevent horizontal scrolling (and possible janitor intervention).
  • Want more info? How to link or How to display code and escape characters are good places to start.
Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others surveying the Monastery: (7)
As of 2024-04-18 10:54 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found