Perl uses reference counting. Every time the code goes over a "my" variable, you are going to get new memory unless Perl can reuse what it had before (and it will it if it can - but Perl doesn't do garbage collection like JAVA).

If you pass a reference to that memory from the: my $trick = "TRICKY"; statement out of a sub, the next time Perl sees the "my", it allocates new memory for it if it sees that what it did before is still in "use" - meaning a reference to it exists. Perl "frees" memory back for its own use when it sees that the reference count to that memory is zero - not well illustrated in this example. The point here is that you get a completely new copy of "TRICKY" every time the sub is called.

My verbage was a bit confusing, but does the code answer the question?

#!/usr/bin/perl use strict; use warnings; my @tricks; for (1..3) { my $ref_to_a_trick = get_a_trick(); push @tricks, $ref_to_a_trick; } print @tricks,"\n"; #SCALAR(0x182b394)SCALAR(0x24920c)SCALAR(0x24925c) #note each "trick reference" points to a different location #@tricks is an array of scalar references foreach my $ref (@tricks) { print "$$ref\n"; #de-reference each "trick" to get the value #TRICKY #TRICKY #TRICKY } sub get_a_trick { my $trick = "TRICKY"; return (\$trick); }
@tricks=(); will "free" the $tricks memory back to Perl (not to the O/S) and Perl will reuse it if it can because no references exists any longer to various memory allocations of "TRICKY".

In reply to Re^3: Scope of lexical variables in the main script by Marshall
in thread Scope of lexical variables in the main script by sophate

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.