Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I access the ref count of a Perl hash?

Tags:

perl

I'm trying to enable the garbage collector of my script to do a better job. There's a ton of memory that it should be able to reclaim, but something is stopping it.

I've used Devel::Cycle a bit and that's allowed me to get closer but I'm not quite there.

How do I find out the current reference count for a Perl hash (the storage for my objects)?

Is there a way to track who is holding a reference to an object? Perhaps a sort of Tie that says, whenever someone points are this object, remember who that someone is.

like image 591
mmccoo Avatar asked Feb 16 '10 22:02

mmccoo


People also ask

How to get reference to a hash in Perl?

To get a hash reference, use the {key=>value} syntax instead, or prefix your variable name with a backslash like: %hash. Dereference a hash with %$hashref, with the $arrayref->{key} arrow for value references, or the %{array_ref_expression} syntax.

What is a hash ref?

A hash is a basic data type in Perl. It uses keys to access its contents. A hash ref is an abbreviation to a reference to a hash. References are scalars, that is simple values. It is a scalar value that contains essentially, a pointer to the actual hash itself.

How do I return a hash value in Perl?

Loop over Perl hash elementsThe keys() function returns a list of hash's keys. The for loop visits each key and assigns it to a special variable $_ . Inside the loop, we access the value of a hash element via its key as $langs{$_} .

How do you reference in Perl?

You can create references for scalar value, hash, array, function etc. In order to create a reference, define a new scalar variable and assign it the name of the variable(whose reference you want to create) by prefixing it with a backslash.


2 Answers

You are looking for Devel::Refcount.

like image 54
willert Avatar answered Oct 23 '22 04:10

willert


If you are worried about returning unused memory to the OS, you should know that is not possible in general. The memory footprint of your Perl program will be proportional to the largest allocation during the lifetime of your program.

See How can I make my Perl program take less memory? in the Perl FAQ list as well as Mini-Tutorial: Perl's Memory Management (as pointed out by @Evan Carroll in the comments).

like image 6
Sinan Ünür Avatar answered Oct 23 '22 03:10

Sinan Ünür