http://www.perlmonks.org?node_id=1006710


in reply to Memory issue with Hash

Perl does re-use memory internally, and may release memory to the OS, although not reliably (but that's OS dependent and not as bad as it sounds in the vast majority of cases).

If you are seeing your program's memory usage increase over time, it's probable you have a memory leak. Setting a hash to undef doesn't guarantee that all references will be garbage-collected, recursively, which is what you might expect. Also, keep in mind undef is not free(); it doesn't de-allocate anything.

First, as is common with GC systems, Perl maintains a reference count to each reference. If you have, say, a map of keys to array refs, and you delete the hash, the arrays will still exist if (and only if) some other thing still references them.

The second bit, which may sound more arcane, is that if, anywhere in your data, you have circular references ($a == $b, but possibly assigned through a longer assignment path as in a circular linked list for example), the memory for $a and $b will never be reused, even if nothing else references $a or $b, unless you break the circular reference.

Usually, breaking circular references isn't obvious and is potentially very expensive. See Scalar::Util's weaken($ref) function, however, for one approach.

If neither of those things seem to describe your problem, perhaps you could post some short sample code for us to have a look at.