in reply to Re: Release memory in hash of hashes
in thread Release memory in hash of hashes

What I am doing is I use Storable and perform
my $word_index_ref = retrieve( $word_index_file );
which allocates a hash of hashes of hashes (or arrays) structure.
At some point I call a function inside this scope which needs memory and I want to release all retrieve() has poped up.

Replies are listed 'Best First'.
Re^3: Release memory in hash of hashes
by GrandFather (Saint) on Aug 18, 2009 at 00:37 UTC

    Then assuming nothing else is referencing parts of the data structure held on to by $word_index_ref, all you need do is:

    $word_index_ref = undef;

    at which point perl will release all the memory allocated to $word_index_ref back to its heap where the memory will be available for reuse. However, do not expect to see the memory footprint for the running Perl application reduce at that point because perl typically does not hand the freed memory back to the OS.


    True laziness is hard work
Re^3: Release memory in hash of hashes
by ig (Vicar) on Aug 18, 2009 at 00:53 UTC

    You can let scope do this for you:

    { my $word_index_ref = retrieve( $word_index_file ); # Use $word_index_ref here } # $word_index_ref is out of scope here

    When the block (scope) in which lexical variable $word_index_ref is declared is exited, the variable goes out of scope and, if there are no remaining references, associated memory is freed. This is one reason for using lexical variables and declaring them in the smallest possible scope. Sometimes an appropriate scope already exists (e.g. the blocks of subroutines, loops and conditionals), but you can create one anywhere.