Perl Scripts ·

Circular References and Memory Leaks in Perl

By Manu Mathew, Technical Lead Engineer · Published 10 November 2017 · Last updated 5 October 2026

Isometric illustration of two linked blocks in a loop, with one link drawn as a thin blue dashed line

A long-running Perl process grows a little with every request until someone restarts it. One common cause is a circular reference: two pieces of data that point at each other, so Perl never frees either.

This note explains why circular references cause memory leaks in Perl, shows the leak in a small tested script, and fixes it with a weak reference.

Quick answer

Perl frees memory by reference counting, so two pieces of data that point at each other never reach a count of zero and stay in memory until the program ends. Break the cycle by weakening one link with weaken from Scalar::Util, usually the reference from a child back to its parent. Weak references don’t keep data alive.

Why do circular references cause memory leaks in Perl?

Perl keeps a count of how many references point at each value, and frees the value when the count drops to zero. A cycle keeps every count above zero.

When a parent object holds its child and the child holds its parent, leaving the scope removes your variables, but each object is still referenced by the other. Neither count reaches zero, so neither is freed, and any DESTROY method doesn’t run until the whole program ends.

How can I see the leak happen?

Give the objects a DESTROY method that prints a message; if the message doesn’t appear when the scope ends, the object is still in memory.

use strict;
use warnings;
use Scalar::Util qw(weaken);

package Node {
    sub new     { my ($class, $name) = @_; return bless { name => $name }, $class }
    sub DESTROY { print "freed $_[0]{name}\n" }
}

sub leaky {
    my $parent = Node->new('parent (leaky)');
    my $child  = Node->new('child (leaky)');
    $parent->{child} = $child;
    $child->{parent} = $parent;      # strong reference back: a cycle
}

sub tidy {
    my $parent = Node->new('parent (weak)');
    my $child  = Node->new('child (weak)');
    $parent->{child} = $child;
    $child->{parent} = $parent;
    weaken($child->{parent});        # the back-reference no longer counts
}

leaky();
print "after leaky(): nothing was freed\n";
tidy();
print "after tidy()\n";
END { print "program ending\n" }
after leaky(): nothing was freed
freed parent (weak)
freed child (weak)
after tidy()
program ending
freed child (leaky)
freed parent (leaky)

The leaky pair is only freed at “global destruction”, when Perl tears everything down at exit. In a script that runs once, that is harmless. In a worker that calls leaky() for every job, memory grows until the process is restarted.

How does weaken fix it?

weaken turns one reference into a weak reference, which still lets you reach the data but no longer counts towards keeping it alive.

use strict;
use warnings;
use Scalar::Util qw(weaken isweak);

my $data = { name => 'config' };
my $copy = $data;
weaken($copy);
print isweak($copy) ? "weak\n" : "strong\n";   # weak
undef $data;                                   # last strong reference gone
print defined $copy ? "still here\n" : "copy is now undef\n";   # copy is now undef

Weaken the link that points “up” or “back”, such as child to parent, and keep the links that express ownership strong. When the last strong reference goes, the data is freed and every weak reference to it becomes undef.

Where do circular references usually appear?

Anywhere data needs to find its way back to whatever holds it:

How do I find cycles in existing code?

Test for them directly, and watch memory in long-running processes.

When I look at an older Perl system with memory that creeps up, this is one of the first things I check, because the fix is usually a single weaken once the cycle is found.

Frequently asked questions

Do circular references matter in short scripts?

Usually not much. Memory is released when the program ends, so a CGI script that runs for a second rarely suffers. They matter in long-running processes, such as daemons, job workers and persistent web applications, where a small leak on every request adds up over hours and days.

Does weaken delete the data?

No. weaken only stops that one reference from counting. The data lives as long as at least one normal reference points to it. Once the last one goes, the weak reference becomes undef, so check it with defined before using it.

How do closures create circular references?

An anonymous sub that uses $self keeps $self alive. If the object also stores that sub, for example as a callback, each holds the other. Capture a weakened copy instead, my $weak = $self; weaken($weak);, and use $weak inside the sub.

Does copying a weak reference keep it weak?

No. A copy of a weak reference is a normal, strong reference, so my $copy = $weak; keeps the data alive again. Weaken the copy as well if it shouldn’t hold on to the data.

Related notes: Perl hashes; multidimensional arrays in Perl; why Perl::Critic flags conditional declarations.

Related reading: Testing legacy Perl code before you change it; Where Perl still belongs; hiring a remote Perl developer.

Need help with Perl code?

If you have Perl code that needs fixing, extending or upgrading, I’m happy to take a look. I work remotely from Kozhikode, Kerala, with teams across India and elsewhere; Perl development and maintenance explains how I help. If you are deciding how to bring someone in, Hiring a remote Perl developer is a short checklist.

You can reach me through the contact section or email me at manu@manu.co.in. A few lines about the system and what you need is a good start.

An earlier version of this note (2017) showed two variables that pointed at each other. This version is rewritten with a tested example and more detail.

Sources: perlref: circular references; Scalar::Util: weaken; perlobj: destructors; Devel::Cycle.

Back to the blog