12/13/2017 - 2:39 PM

Reference Counts

Perl uses a memory management technique known as 'reference counting'. Every Perl value has a counter attached to it, internally. Every time a reference is added to that value, its counter goes up by 1, and is decreased when a reference goes away. When the counter reaches zero, Perl can safely recycle that value to save memory.

# Example: consider this filehandle opened in this inner scope:

say 'file not open';

  # open and edit the file
  open my $fh, '>', 'inner_scope.txt'; 
  fh->say('file open here');

say 'file closed here';

# $fh is only in scope in the block, its value never leaves the block. 
# When execution reaches the end of the block, Perl recycles the variable $fh and decreases the reference count of the filehandle.
# This is because the filehandle's reference count has reached zero, so Perl destroys it to reclaim memory.
# It also calls close() on the filehandle implicitly as part of the process.