Why my sub cannot get hidden in the scope of function such in
use strict;
sub out{
my sub this{my $n=9;print "\n$n"} my $i=7; my $j=3
}
&this;
9
Please help solve
Why my sub cannot get hidden in the scope of function such in
use strict;
sub out{
my sub this{my $n=9;print "\n$n"} my $i=7; my $j=3
}
&this;
9
Please help solve
As described in the documentation in perldoc perlsub, a lexical subroutine is only visible inside the block they are created:
These subroutines are only visible within the block in which they are declared...
You try to call the sub outside the block, therefore Perl cannot see it. This is also the entire point of using lexical scope: You are trying to restrict the range.
If you had use warnings
enabled you would get the warning:
Undefined subroutine &main::this called at ...
You have to use the lexical sub inside the block -- in this case another sub -- like this:
sub out {
my sub this {
....
}
this(); # <---- visible here
}
this(); # wrong, not visible here
Also, using &
when calling a sub has a special meaning. As described in perlsub:
&NAME; # Makes current @_ visible to called subroutine.
The normal way to call a sub is by adding parens after: this()
. The different ways to call a sub are also listed in perldoc perlsub. Note that there is hidden functionality in the different styles.
NAME(LIST); # & is optional with parentheses.
NAME LIST; # Parentheses optional if predeclared/imported.
&NAME(LIST); # Circumvent prototypes.
&NAME; # Makes current @_ visible to called subroutine.