http://qs321.pair.com?node_id=187246

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

Hi all.

A former college professor of mine and I were discussing memory leaks and garbage collection in various scripting languages the other day, and he asked me how this issue was handled in perl ( he bought 'Learning Perl - 3rd edition' last week ). After explaining what I knew about references ( I'm still learning ), he asked me if I could research the topic so we could discuss it in more depth.

So far, I have learned that perl handles this topic through a mechanism called reference counting. It seems each block of memory has an internal reference 'count' that stores the number of references which contain an address. If / When this number becomes zero, the memory that occupied that space is released ( freed ).

{ # Start of naked block. my $ref; { my $num = 20; $ref = \$num; } } #End of naked block.

When $num is created, the reference count becomes 1. Then the reference count is incremented to 2 when $ref is assigned a reference to $num. When we reach the end of the inner block, $num goes out of scope and we can no longer reference it through $num. This has the effect of decrementing the reference count by 1. At the end of the outer block, $ref goes out of scope thereby dropping the reference count to zero. This will free any memory previously occupied.

The problem occurs when one reference refers to another.
{ my $ref; my $ref2 = \$ref; $ref = \$ref2; }

The reference cannot drop to zero and the memory it is occupying will never be freed ( the dreaded memory leak ). This can bring a machine to it's knees if left 'unattended'. Does anyone know of an efficient way to break circular references? Aside from assigning a value to the scalar $ref ( i.e. $ref = 15 ), I don't see a solution.

Thanks in advance,
-Katie.