views:

228

answers:

3

Unlike Java, Perl uses reference count for garbage collection. I have tried searching some previous questions which speak about C++ RAII and smart pointers and Java GC but have not understood how Perl deals with the circular referencing problem.

Can anyone explain how Perl's garbage collector deals with circular references? Is there any way to reclaim circular referenced memory which are no longer used by the program or does Perl just ignores this problem altogether?

+5  A: 

According to my copy of Programming Perl 3rd ed., on exit Perl 5 does an "expensive mark and sweep" to reclaim circular references. You'll want to avoid circular references as much as possible because otherwise they won't be reclaimed until the program exits.

Perl 5 does offer weak references through the Scalar::Utils module.

Perl 6 will move to a pluggable garbage collected scheme (well, the underlying VM will have multiple garbage collection options and the behavior of those options can have an effect on Perl). That is, you'll be able to choose between various garbage collectors, or implement your own. Want a copying collector? Sure. Want a coloring collector? You got it. Want reference counting? Why not?

Max Lybbert
Nit: Perl 5 uses reference counting. That is a garbage collection scheme.
tsee
OK, I modified the reference to Perl 6 garbage collection.
Max Lybbert
Thanks for updating the answer. NB: Pluggable garbage collectors seems like a horrible idea. A great way to slow down things and/or produce dubious action at a distance when plugging garbage collectors which make different promises about GC time.
tsee
I have no idea why they went for a pluggable architecture, other than (1) to say "this really is implementation defined territory" and (2) to avoid making a decision. They also went for a pluggable regular expression architecture, and that makes even less sense to me.
Max Lybbert
+1  A: 

Have a look at Proxy Objects.

Pedro Silva
+1  A: 

Perl applies a mark-and-sweep alternate GC in some occasions (when a thread dies, I think) in order to reclaim circular references. Note that the "every value is a string" Perl stanza makes it difficult to create true circular references; this is feasible, but "normal" Perl code does not, which is why reference counting works well with Perl.

Thomas Pornin
Quick way to leak one SV perl call `sub leak { my $r; $r = \$r; }`While this is a contrived example it's not hard to do the equivalent without noticing it.
Ven'Tatsu