In Functions§

See primary documentation in context for Closures.

All code objects in Raku are closures, which means they can reference lexical variables from an outer scope.

sub generate-sub($x) {
    my $y = 2 * $x;
    return sub { say $y };
    #      ^^^^^^^^^^^^^^  inner sub, uses $y
}
my $generated = generate-sub(21);
$generated(); # OUTPUT: «42␤»

Here, $y is a lexical variable inside generate-sub, and the inner subroutine that is returned uses it. By the time that inner sub is called, generate-sub has already exited. Yet the inner sub can still use $y, because it closed over the variable.

Another closure example is the use of map to multiply a list of numbers:

my $multiply-by = 5;
say join ', ', map { $_ * $multiply-by }, 1..5;     # OUTPUT: «5, 10, 15, 20, 25␤»

Here, the block passed to map references the variable $multiply-by from the outer scope, making the block a closure.

Languages without closures cannot easily provide higher-order functions that are as easy to use and powerful as map.