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

I have inherited a fairly large script that fails to run in its entirety due to memory issues. The script has hundreds of variables and I have no idea which one might be to blame...

Ideally, I would like to be able to output the refcount of each variable in the script at various points throughout the program. This way, I could see what needs to be undef'ed.

Is there a function that will return a hash (or something) containing the refcount (or perhaps, as a backup the memory usage) of all the variables in the script?

Thanks,
Perldough

Replies are listed 'Best First'.
Re: Obtaining refcount for all variables
by bulk88 (Priest) on Aug 01, 2012 at 00:22 UTC
    If you want the refcount, that is simple.
    $s = "you are ".int(rand(11))." on a score of 0 to 10"; print "refcount is ".Internals::SvREFCNT($s)."\n";
    result
    refcount is 1
    Is the refcount the correct way to figure out whats being a memory hog? maybe yes, if you trying to look for something that is overreferenced, in most of the time no. I suggest looking at Devel::LeakTrace (used it personally, it never found a SV leak, it was a malloc C leak). Next question is, are your memory problems from the perl script you are running, or from XS modules you are running? And do you have a memory leak (steady slow increase in ram over time), or are simply trying to reduce runtime ram bloat of the process?

    You problems can be as simply as an array that is shifted/pushed onto and never poped/unshifted, or it can be a circular reference, or a unfixable (by you, only by p5p) interp specific bug.

    You say you want to know what to undef, was your script written entirely with global and the time cost to convert it to a "use strict" script is too high for you?

    Also look at Devel::Gladiator, I've never used it personally.