in reply to anonymous vs named subroutines as closures
Demonstration of "will not stay shared":
sub outer { my ($x) = @_; sub inner { say $x; } inner(); } # Warns Variable "$x" will not stay shared outer(4); # Prints 4 outer(6); # Prints 4!!!
Here's what's going on.
sub named { ... }
is more or less the same as
BEGIN { *named = sub { ... }; }
As such, it only captures once, when the sub is compiled.
In the above code, when outer goes out of scope, $x would normally be cleared. But since the closure still references it, a new $x is a created instead. From this point on, the $x in inner is different from the $x is outer; it "didn't stay shared".
|
|---|