PERL / CHAPTER 06

Lexical closures and private state

Intermediate

Create independent stateful helpers without package globals.

By the end of this chapter

  • Capture lexical bindings in anonymous subs
  • Distinguish shared closures from separate factories
  • Keep updates behind a narrow callable interface

The idea

An anonymous subroutine can retain access to lexical variables from the scope where it was created. Returning that subroutine creates a closure whose state can outlive the factory call. Two calls to the factory create independent lexical bindings, while copying one coderef produces another reference to the same callable and captured state.

This pattern is useful for counters, configurable predicates, and small caches. Keep the captured state private when callers should update it only through the documented operation. Avoid making an ordinary package variable appear private merely by hiding its name in a helper. Test interleaved calls to two factory results to reveal whether their state is actually independent.

Perl example
use strict; use warnings;
sub counter { my $n=0; return sub { ++$n }; }
my $a=counter(); my $b=counter();
print $a->()," ",$a->()," ",$b->(),"\n";
Result
1 2 1

Each factory call owns a different lexical n, while repeated calls through a update one captured binding.

Try it yourself

Create a threshold predicate factory whose callers cannot directly modify its captured threshold.

Use your own editor for this exercise. Runnable challenges on CodeQuest are available for JavaScript, Python, and SQL.

CHECK YOUR UNDERSTANDING

Chapter checkpoint

Which declaration creates captured lexical state inside a factory?