100% Free Forever
AI-Powered Learning
Industry Expert Content
Certificates & Badges
Learn At Your Own Pace
Programming

Closures in Perl

Understand how Perl closures capture lexical variables to create private state, counters, and callback generators using anonymous subroutines.

Advanced PerlAdvanced10 min readJul 10, 2026
Analogies

What Is a Closure

A closure is an anonymous subroutine that retains access to the lexical (my) variables that were in scope at the point it was defined, even after the enclosing scope has technically finished executing. In Perl, this happens naturally because sub { ... } captures a reference to the surrounding lexical pad, not a copy of the values at that instant. Each time the outer function runs and creates a new anonymous sub, that sub gets its own private binding to a fresh set of lexicals, which is what makes closures useful for generating multiple independent stateful functions from one factory routine.

🏏

Cricket analogy: A bowling machine calibrated to a specific batsman's stance at setup time keeps 'remembering' that stance setting even after the coach who configured it has walked away, just as a closure keeps referencing the lexicals from its defining scope.

Lexical Scoping with my and Anonymous Subs

The classic closure pattern is a factory function: an outer sub declares a my variable, then returns an anonymous sub { ... } that reads or modifies that variable. Because the returned sub keeps a live reference to the lexical rather than a snapshot, calling the factory twice produces two independent closures, each with its own private counter, cache, or accumulator that the caller cannot access except through the returned sub itself. This gives you encapsulated, mutable state without declaring a package or object, which is why closures are often described as 'poor man's objects' in Perl.

🏏

Cricket analogy: Two different bowling machines set up in adjacent nets each track their own private ball count independently, so incrementing one machine's counter never affects the other, just like two calls to a counter factory yielding independent closures.

perl
sub make_counter {
    my $count = shift // 0;
    return sub { return $count++; };
}

my $c1 = make_counter();
my $c2 = make_counter(100);

print $c1->(), "\n";  # 0
print $c1->(), "\n";  # 1
print $c2->(), "\n";  # 100
print $c1->(), "\n";  # 2 -- c1 and c2 are independent

Common Uses: Counters, Callbacks, Private State

Beyond simple counters, closures are the standard way to build memoized functions, event-handler callbacks that need context, and iterators that yield the next value on each call without exposing the underlying data structure. A memoizing closure captures a private %cache hash and checks it before doing expensive work; a GUI callback closure captures the specific widget or record ID it should act on when the button is eventually clicked, long after the loop that created the button has finished. This pattern shows up heavily in event-driven code, Mojolicious route handlers, and any API that takes a coderef parameter.

🏏

Cricket analogy: A DRS review system caches the last few ball-tracking calculations privately so a repeated review of the same delivery doesn't recompute the trajectory, exactly like a memoizing closure checking its private cache hash first.

A well-known pitfall is creating closures inside a loop that reuses the same lexical variable across iterations; if the loop variable is declared outside the loop body, or the loop doesn't create a fresh lexical per iteration, every closure ends up sharing one final value instead of each capturing its own. Perl's foreach loop with 'my $i' in the loop header actually creates a new lexical binding on each pass, which avoids this trap, but a C-style for (my $i = 0; ...) loop shares a single $i across all iterations and will produce closures that all report the same final value.

🏏

Cricket analogy: If every fielding position's reminder note is written referencing one shared scoreboard variable instead of a fresh copy per fielder, all ten reminders end up showing the final over's number instead of each fielder's own assigned over.

for my $i (@list) { push @subs, sub { print $i } } is safe because 'my $i' in a foreach header gets a fresh lexical binding each iteration. But for (my $i = 0; $i < @list; $i++) { push @subs, sub { print $i } } is dangerous — all closures share the same $i and will print the final value after the loop ends.

Closures vs Objects

Closures and Perl's object system (bless-ed hashrefs with method dispatch) both provide encapsulated, private state, but they trade off differently: a closure is lightweight, requires no package declaration, and hides its state so completely that not even the closure's own code can accidentally expose the raw variable, whereas an object gives you inheritance, multiple named methods operating on shared state, and introspection via ref() and isa(). For a single-purpose stateful function — a counter, an iterator, a rate limiter — a closure is usually simpler and faster to write; once you need several related operations sharing the same state with a clean external API, a small class is usually more maintainable.

🏏

Cricket analogy: A single ball-tracking function closed over its own hidden speed-gun reading is like a quick, single-purpose closure, whereas a full player-management object with batting, bowling, and fielding methods sharing one player record is like a class.

perl
# Closure-based rate limiter: one purpose, private state
sub make_rate_limiter {
    my ($max_calls) = @_;
    my $calls = 0;
    return sub {
        return 0 if $calls >= $max_calls;
        $calls++;
        return 1;
    };
}

my $allow = make_rate_limiter(3);
print $allow->() ? "ok\n" : "blocked\n" for 1..4;
# ok, ok, ok, blocked
  • A closure is an anonymous sub that retains a live reference to the lexical variables in scope when it was defined.
  • Each call to a closure-generating factory function produces an independent closure with its own private state.
  • Closures enable counters, memoization caches, and callbacks that carry context without global variables.
  • 'for my $i (@list)' creates a fresh lexical per iteration, so closures built inside it correctly capture distinct values.
  • C-style for-loops with a shared 'my $i' outside the loop body are a classic closure trap — all closures end up sharing one final value.
  • Closures give lightweight single-purpose encapsulation; blessed objects are better once you need several related methods sharing state.
  • Closures are sometimes called 'poor man's objects' because they hide state as completely as private object attributes do.

Practice what you learned

Was this page helpful?

Topics covered

#Programming#PerlStudyNotes#ClosuresInPerl#Closures#Perl#Closure#Lexical#Functions#StudyNotes#SkillVeris