Beefy Boxes and Bandwidth Generously Provided by pair Networks
laziness, impatience, and hubris

Re^2: Do subroutine variables get destroyed?

by eyepopslikeamosquito (Chancellor)
on May 08, 2016 at 16:37 UTC ( #1162494=note: print w/replies, xml ) Need Help??

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).

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 { open(my $fh, "<", "f.tmp") or die "open error f.tmp: $!"; # ... process file here die "oops"; # if something went wrong # ... }
note that $fh is automatically closed immediately the function exits.

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.

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1162494]
and dust plays in a shaft of sunlight...

How do I use this? | Other CB clients
Other Users?
Others browsing the Monastery: (5)
As of 2017-10-21 00:23 GMT
Find Nodes?
    Voting Booth?
    My fridge is mostly full of:

    Results (268 votes). Check out past polls.