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.
| [reply] |
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).
| [reply] |
- 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.
- You create a reference to the hash, so the hash's REFCNT increases to two.
- 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.)
- 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.)
| [reply] [d/l] [select] |
Thank you for your wisdom | [reply] |