in reply to sub routines inside subroutines
The respondents gently reminded me that nested subroutines declared at compile time normally exist in the symbol table. That is, they're not made private to the enclosing subroutine.
However, if you do nest a subroutine and refer to the enclosing scope's variables, you'll probably get a variable %s will not stay shared warning, for good reason.
In the following code, what's the scope of $x:
Because you can call inner() from anywhere in the package, or anywhere you qualify it properly, it doesn't function as a closure. The proper solution in a case like this is to use a real closure:sub outer { my $x = shift; sub inner { return $x; } }
You'd obviously want to do more there, but that's one way to handle things properly, letting Perl worry about scoping for you.sub outer { my $x = shift; my $inner = sub { return $x }; }
|
|---|