As the example below shows, defining a subroutine with
sub within another subroutine and then calling it from within the enclosing subroutine works (although I don't think it's considered quite kosher), but really buys you nothing because the enclosed subroutine is still global in scope.
I have seen the trick on PM of local-izing a glob within a subroutine and then defining a named subroutine via that glob, but otherwise the approach for private subroutines seems to be to use anonymous subs defined within a sub.
The statement my sub foo { ... } produces a "my sub" not yet implemented ... error in 5.10 (and before AFAIR), so someone is thinking about this!
>perl -wMstrict -le
"print level2();
sub level1 {
sub level2 { return 'level2(): foo' }
print 'level1(): ', level2();
}
level1();
print level2();
"
level2(): foo
level1(): level2(): foo
level2(): foo
Updates:
-
After reading Joost's reply, I remembered the 'stupid local trick' referred to above. Perhaps someone else can say if this approach differs at all (other than by supplying a local named subroutine) from the anonymous-subroutine-assigned-to-lexical-variable approach; I can see no difference.
>perl -wMstrict -le
"sub level1 {
my $x = shift || 'default';
local *foo = sub { return 'foo' . $x };
print foo();
}
level1('bar');
level1();
foo();
"
foobar
foodefault
Undefined subroutine &main::foo called at -e line 1.
-
A 'stupid local trick'? Well, maybe not. See ikegami's detailed reply to Re^3: Defining a sub within a sub: OK? below: there is an advantage.