Named subroutines never go out of scope; they're global - bound to a package just like global variables.
Anonymous subrefs can go out of scope, just like any other variable, but, just like any other variable, you can pass them around:
sub call {
my ($arg1,$arg2) = @_;
my $callback = sub {
my ($arg3) = @_;
return $arg1 + $arg2 + $arg3;
};
call_func_needing_callback($callback);
}
# or even
sub call {
my ($arg1,$arg2) = @_;
call_func_needing_callback( sub {
my ($arg3) = @_;
return $arg1 + $arg2 + $arg3;
});
}
Also note that there are scoping issues with defining named closures within other subroutines (this probably has to do with named subroutines being global), while unnamed subroutines/closures will work as real lexical closures.
|