Subroutines & signatures

Closures

Full

Blocks that capture the lexical variables in scope where they were created.

A closure is a block or sub that captures the variables in scope where it was defined and keeps them alive. Each time the enclosing scope runs, a fresh set of captured variables is made — so closures created separately don't share state.

Capturing a variable #

The returned block below keeps $n alive after make-counter has returned, and mutates it on each call.

sub make-counter {
    my $n = 0;
    return { $n++ };
}
my $c = make-counter();
say $c();
say $c();
say $c();
Output
0
1
2

Independent captures #

Every call to make-counter creates a new $n, so two counters are independent.

sub make-counter { my $n = 0; return { $n++ } }
my $a = make-counter();
my $b = make-counter();
say $a();
say $a();
say $b();
Output
0
1
0

$a advances to 1, but $b starts fresh at 0 — each closure has its own $n.

Notes #