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

What happens when a reference to a non-primitive (e.g. hash) local function variable declared as "my $x" is returned to the caller? Does perl know to handle this non-best practice programming and keep its reference count, or does the var's memory gets released when leaving the function (i.e. from the function's stack)? Exmaple: sub x { my %some_hash; # Manipulate %some_hash return \%some_hash; }
  • Comment on Reference to a non-primitive (e.g. hash) local function variable is returned to the caller

Replies are listed 'Best First'.
Re: Reference to a non-primitive (e.g. hash) local function variable is returned to the caller
by Corion (Patriarch) on Sep 21, 2011 at 09:44 UTC

    This is why Perl uses reference counting. Perl knows what memory is still referenced and keeps it alive, no matter where it is referenced from (within Perl). Allocating and passing around values this way is a best practice in Perl, while it may or may not be a best practice in other languages with unmanaged memory, like C.

Re: Reference to a non-primitive (e.g. hash) local function variable is returned to the caller
by Perlbotics (Archbishop) on Sep 21, 2011 at 09:46 UTC

    Short: It's possible and legal.

    It's non best-practice programming for languages like C, C++, etc. where returning pointer to object from the stack is an error. But this is Perl and Perl usually keeps track of the variables in use (ref-counts) and garbage collects them when necessary.
    There are edge-cases with cyclic dependencies though (see: weaken in Scalar::Util).

Re: Reference to a non-primitive (e.g. hash) local function variable is returned to the caller
by ikegami (Patriarch) on Sep 21, 2011 at 19:38 UTC
    1. my creates a new hash (like new would in another language). The sub holds a references to the hash, so the hash's REFCNT is one.
    2. You create a reference to the hash, so the hash's REFCNT increases to two.
    3. You exit the sub, so the sub release its reference to the hash, so the hash's REFCNT drops to one. (If it wasn't for the reference you created, the hash's REFCNT would now be zero, and the hash would get freed.)
    4. If/when you eventually destroy the reference, the hash's REFCNT will drop to zero, freeing the hash (and in turn reducing the REFCNT of its values, possibly freeing them).

    (The actual implementation is somewhat more complicated, but the differences aren't relevant here.)

Re: Reference to a non-primitive (e.g. hash) local function variable is returned to the caller
by o_ganot (Initiate) on Sep 21, 2011 at 10:46 UTC
    Thank you for your wisdom