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

This post answers a few common questions and misconceptions about Perl's memory management.

Lexical variables don't get freed at end of scope

Lexical variables don't get freed at end of scope. They are cleared on scope exit to give you the apperance of a fresh variable. This is an optimisation that should be transparent to you.

On scope exit, if anything prevents the variable from being resused (e.g. if there are remaining references to the variable), the existing variable becomes anonymous and a new variable is allocated.

Clearing a variable does not free the memory it uses

It was previously mentioned that variables on cleared on scope exit. Variables can also be cleared as follows:

$s = undef; @a = (); %h = ();

Clearing a variable frees no memory directly. The buffer of a string is marked as being unused, but it remains allocated for later use. The underlying array of pointers in arrays and hashes is cleared, but it remains allocated for later use. This is an optimisation that should be transparent to you.

As a result of a variable being cleared, referenced variables (incl array elements) have their refcount lowered, and that may free those variables. But not the variable being cleared.

undef does not free a variable

undef can be used to clear a variable.

undef $s; undef @a; undef %h;

undef does do more than clear the variable. It also frees any buffers the variable has.

$ perl -MDevel::Peek -e' $s = "abc"; Dump $s; $s = undef; Dump $s; undef $s; Dump $s; ' SV = PV(0x814fb00) at 0x814f69c REFCNT = 1 FLAGS = (POK,pPOK) <-- Var contains a string PV = 0x81651b8 "abc"\0 CUR = 3 LEN = 4 SV = PV(0x814fb00) at 0x814f69c REFCNT = 1 FLAGS = () <-- Var is undefined PV = 0x81651b8 "abc"\0 <-- String buffer still CUR = 3 allocated after clearing LEN = 4 SV = PV(0x814fb00) at 0x814f69c REFCNT = 1 FLAGS = () <-- Var is undefined PV = 0 <-- undef freed the buffer

This function is rarely useful.

However, undef will never free a variable. Clearing the variable may result in the reduction of the ref counts of other variables, which may free those variables. But not the variable that was passed to undef.

Freeing variables may result in no change in available system memory

You can't rely on memory being returned to the system, but it can happen.

If and when memory is returned to the OS is dependant on the memory allocation mechanism perl was compiled to use. You may also see differences between system using the same memory allocation mechanism. It's also possible that a mechanism will only ever release the large blocks it allocated.

The default memory allocation mechanism varies by OS. You are more likely to see memory being released to the OS on Windows.