http://qs1969.pair.com?node_id=801235


in reply to Re: Defining a sub within a sub: OK?
in thread Defining a sub within a sub: OK?

There's no sane way in which perl could handle a call to b() from the outside.

However there's nothing wrong with defining an anonymous subroutine inside another sub. Actually it's quite common, and used very often in functional programming.

Those two points are related: logically, any call to a() would redefine b() in that code, like my example below, which would only be silly. Also, that would mean that you couldn't call b() before calling a() at least once. But named subroutines are defined only once, at compile time*, which makes the whole construct iffy.

sub a { my $x = 3; *b = sub { print $x, $/; }; }
* The reasoning behind sub NAME { } constructs being realized early is so that you can call subroutines even if their definition is "later" in the code.