← Back to Perl Course | Chapter 6: References | Lesson 7 of 7

Closures

An anonymous subroutine remembers the variables that were in scope when it was created.

In this page:

  1. Closures

Closures

When an anonymous subroutine uses a my variable from the surrounding scope, Perl keeps that variable alive for as long as the subroutine exists. Each call to a function that creates such a subroutine gets its own fresh copy of the variable. This lets you build counters, generators and other small objects without any package machinery.

Note: Perl frees data when the last reference to it disappears, so a closure keeps its captured variables alive.

Example: Closures

perl
use strict;
use warnings;

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

my $c1 = make_counter(1);
my $c2 = make_counter(100);
print "c1: ", $c1->(), " ", $c1->(), " ", $c1->(), "\n";
print "c2: ", $c2->(), " ", $c2->(), "\n";
print "c1 again: ", $c1->(), "\n";

my @subs;
for my $i (1 .. 3) {
    push @subs, sub { return $i * 10; };
}
print "loop closures: ", join(", ", map { $_->() } @subs), "\n";

# Output:
# c1: 1 2 3
# c2: 100 101
# c1 again: 4
# loop closures: 10, 20, 30
Common Mistakes
  1. Expecting every closure created in a loop to share one variable
  2. Forgetting that each call to the factory makes a new independent counter
  3. Using a global variable when a captured my variable would be safer
Chapter Summary
  • Closures capture surrounding my variables
  • Each creation gets its own copy
  • Captured variables stay alive with the closure
  • Closures make counters and generators
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.