in reply to Release memory in hash of hashes

In all likelihood, if your data is of a size where you need to be worried about freeing the memory, you'd be better off to investigate other ways of storing it, such as a database, that don't require it to all be in memory at once. Maybe if you explain the reason you are worried about memory consumption to us, we could understand what you're trying to do better and perhaps suggest a better alternative.

Getting away from trying to micromanage memory allocation is one of the principal advantages of modern scripting languages--why exactly are you trying to out-think the compiler?

Replies are listed 'Best First'.
Re^2: Release memory in hash of hashes
by vit (Friar) on Aug 17, 2009 at 15:30 UTC
    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.

      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

      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.