views:

97

answers:

2

I'm trying to fix my code to enable Perl to recover unneeded data by weakening references and breaking cycles.

I recently asked a question on How to access Perl ref counts and the answer has been working well for me.

For some of my objects, the reference count is > 1 and I don't know why.

Is there a way for me to add a callback or something to help me know when a reference count is incremented? I want to know who is referencing an object.

+5  A: 

Implement a Devel::XXX package that inspects the refcounts of your objects?

package Devel::Something;
# just emulating Devel::Trace here
# see http://cpansearch.perl.org/src/MJD/Devel-Trace-0.10/Trace.pm
sub DB::DB {
    if ($Devel::Something::CHECK) {
        my ($package, $file, $linenumber) = caller;
        ... inspect current refcounts
        ... if any have changed, print out the details
        ...    including current package/file/linenumber
        $Devel::Something::CHECK = 0;  # disable until it's enabled again
    }
}
1;

# my program
... do some stuff ...
$Devel::Something::CHECK = 1;
... do some more stuff ...
$Devel::Something::CHECK = 1;

$ perl -d:Something my_program.pl ...

You could sprinkle $Devel::Something::CHECK = 1 statements at appropriate places throughout your code, or change the condition in DB::DB to run at regular intervals (e.g., if (++$Devel::Something::CHECK % 100 == 0) { to inspect after every 100 statement evaluations).

mobrule
+1 This is a nice one!
tsee
A: 

Perl values only keep track of their weaken references, not their hard ones. There seems to be no way to add a callback for such a think. You'll have to check the refcounts yourself and do your math from that.

Leon Timmermans