Lesson 35 of 55
9 mins readPython Anonymous Subroutines & Closures
In Plain English
Perl supports first-class functions: `my $fn = sub { ... };`. An anonymous subroutine that captures variables from its enclosing scope is a closure.
Deep Dive: How It Works
Code Reference: `my $sub_ref = sub { my $msg = shift; print "$msg\n"; };` called as `$sub_ref->("Hi")`.
Closures: Retain access to private lexical variables even after the parent scope has exited.
Factory Pattern: Generating configured math or validator functions on the fly.
Core Rules to Remember

Code Reference (->()): Invoke a code reference using arrow syntax: `$coderef->($arg)`.

Closures Encapsulate State: Encapsulate private state without global variables.
Live Interactive Example
Hit Run Code to see it liveGenerating Counters with Closures
Python 3.12
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
Output Console
Click "Run Code" to view the rendered output.
How it works: Each closure maintained its own isolated $count variable.
Your Turn: Micro Challenge
No pressure! Edit the starter code below and test your solution with instant feedback.
Micro Exercise
Build Multiplier Closure
Write `sub make_multiplier { my $factor = shift; return sub { my $n = shift; return $n * $factor; }; }`
Create `my $triple = make_multiplier(3);` and print `"Triple 7: " . $triple->(7) . "\n"`.
1
2
3
4
5
Sandbox Output
Click "Run & Check" to test your solution.
Finished reading and practicing?
Mark this lesson as completed to update your course progress.