How to find the amount of physical memory occupied by a hash in Perl?
hash, memory, perl
Solution
Devel::Size is the answer to your question. (Note that Devel::Size will temporarily allocate a significant amount of memory when processing a large data structure, so it's not really well suited to this purpose.)
However, Cache::SizeAwareMemoryCache and Tie::Cache already implement what you're looking for (with somewhat different interfaces), and could save you from reinventing the wheel.
Memoize is a module that makes it simple to cache the return value from a function. It doesn't implement a size-based cache limit, but it should be possible to use Tie::Cache as a backend for Memoize.
Problem
I have a Perl script where I maintain a very simple cache using a hash table. I would like to clear the hash once it occupies more than n bytes, to avoid Perl (32-bit) running out of memory and crashing. I can do a check on the number of keys-value pairs: ``` if (scalar keys %cache > $maxSize) { %cache = (); } ``` But is it possible to check the actual memory occupied by the hash?