Perl uses a method called reference counting to ensure that memory stays allocated as long as there is at least one reference pointing to it. The code you've showed is fine. On every call of the sub, a new array will be allocated, and the reference pointing to it will keep it alive, even after the sub ends.

sub foo { my $m = shift; my @array = ($m*1, $m*2, $m*3); return \@array; } my $x = foo(2); my $y = foo(3); use Data::Dump; dd $x; # [2, 4, 6] dd $y; # [3, 6, 9] $x = undef; # *now* the memory for that array is freed

Update: For more details, see perlref.


In reply to Re: returning reference of a variable defined inside a subroutine. by haukex
in thread returning reference of a variable defined inside a subroutine. by aswingeo

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.