Perl uses a reference counting algorithm for automatic memory management: each variable has a reference count. When the count reaches zero, the memory is freed. In most cases, this works transparently — unused variables are removed as soon as they go out of scope.
The problem arises with circular references (for example, an object refers to itself or two structures refer to each other). In this case, the reference count will never reach zero, and memory will not be freed.
To prevent leaks, the Scalar::Util::weaken module is used — it allows the creation of "weak" references that do not increase the reference count.
Example:
use Scalar::Util qw(weaken); my $a = {}; my $b = { ref => $a }; $a->{ref} = $b; weaken($a->{ref}); # now there is no circular strong dependency
Is it correct to assume that Perl always automatically frees all unused memory, even in the presence of complex interrelated structures?
Answer and example:
No! In the case of circular references, Perl will not be able to free memory automatically unless weaken is used:
my $a = {}; $a->{self} = $a; # cycle # $a will never be automatically removed — manual break or weakening of the reference will be required
Story 1: On a large Perl web service, there was a memory leak — user sessions stored references to each other in a hash, and no one used weak references. The service consumed all resources and crashed within a day, requiring restarts.
Story 2: A custom ORM created cycles between User and Group objects, each referencing the other. After going out of scope, the objects remained in memory — the service gradually "bloated" to dozens of gigabytes!
Story 3: Using anonymous subroutines ("closures") as class methods that refer to
$selfled to leaks with each object creation until an analyzer was introduced that detected circular references and indicated the need forweaken.