<p>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. </p>

<p>I can do a check on the number of keys-value pairs:</p>

<pre><code>if (scalar keys %cache &gt; $maxSize)
 {
 %cache = ();
 }
</code></pre>

<p>But is it possible to check the actual memory occupied by the hash?</p>

You're looking for
Devel::Size
NAME
Devel::Size - Perl extension for finding the memory usage of Perl variables
SYNOPSIS
```
```
use Devel::Size qw(size total_size);

my $size = size("A string");
my @foo = (1, 2, 3, 4, 5);
my $other_size = size(\@foo);
my $foo = {a => [1, 2, 3],
        b => {a => [1, 3, 4]}
       };
my $total_size = total_size($foo);
```
```