in reply to Re: Do subroutine variables get destroyed?
in thread Do subroutine variables get destroyed?

To elaborate further on GrandFather's point that perl uses a reference-counted garbage collector, note that with Perl you get "deterministic destructors" for free; i.e. in perl, you are guaranteed that an object is destroyed (and destructor called) immediately its reference count goes to zero. BTW, deterministic destructors are a feature of the C++ RAII idiom yet are problematic when using a tracing garbage collector, such as that used by Java, which is why Java has a "finally" clause (see also Dispose pattern). See also Finalizer (wikipedia).

You can use deterministic destructors to good effect in Perl with lexical file handles, which are automatically closed when the file handle goes out of scope; for example in:

sub fred { # Lexical $fh is known from point of declaration (next line) to en +d of scope open(my $fh, "<", "f.tmp") or die "open error f.tmp: $!"; # ... process file here # We assume no references to $fh are created in and returned from +this sub # (if you did that reference count of $fh would not be zero on sub + exit) # ... die might be called ... (that's ok, can be caught via block +eval) # ... there can be multiple return statements ... return; }
note that $fh is automatically closed immediately the function exits because the $fh variable goes out of scope at end of function ... and when $fh goes out of scope, its reference count goes to zero and its destructor is automatically and immediately called to close the file handle. No need for an explicit close.

A drawback to reference counting, that tracing GCs solve, is the dreaded circular reference problem. For an example of how to deal with circular references in Perl, see Eliminate circular reference memory leak using weaken.

As to when the memory is actually released back to the OS, see the answers to this question.