Say you have a complicated method and you want to have an embedded subroutine there, that won't be visible elsewhere - like Pascal or D allow. No problem - you make a lexical code reference:
my $func = sub { my ($param1, $param2) = @_; do { foo }; return $bar; }
Then you call this subroutine like this:
$func->($something, $otherthing);But what if you want this subroutine to be recursive? Inside its body, the $func variable isn't defined yet (right hand side of assignment is evaluated first), so you can't just say
my $func = sub { do { something }; $func->($param1, $param2); }
The solution is obvious - you have to add a parameter to the function where you'll pass itself:
my $func = sub { my ($func, $param1, $param2) = @_; do { something }; $func->($func, $param1, $param2); }
Of course you'll then have to adapt the first call as well:
$func->($func, $something, $otherthing);
Back to
Meditations