spx2 has asked for the wisdom of the Perl Monks concerning the following question:

If one defines a sub in a closure like this

{ my $sub_in_closure = sub jojo { ... } }
How can I use it outside the closure ?(or mustn't I?)

Replies are listed 'Best First'.
Re: calling from outside the closure a sub defined in a closure
by Anno (Deacon) on Sep 19, 2007 at 09:48 UTC
    Your code doesn't show a closure, just a bare block that defines a coderef (which might itself be a closure) in its lexical scope. If you want to access that outside the block, you must find a way to pass the coderef outside. A sub could return it, probably among other things.

    This looks like a somewhat convoluted design.

    Anno

Re: calling from outside the closure a sub defined in a closure
by derby (Abbot) on Sep 19, 2007 at 12:17 UTC

    Anno was right, that's not a closure. Here's the typical example of a closure:

    #!/usr/bin/perl use strict; use warnings; my $plus_5 = adder( 5 ); my $plus_10 = adder( 10 ); print $plus_5->(2), "\n"; print $plus_10->(3), "\n"; sub adder { my $base = shift; return sub { $base + shift; } }

    -derby
Re: calling from outside the closure a sub defined in a closure
by moritz (Cardinal) on Sep 19, 2007 at 09:30 UTC
    If you want to use it outside the sub, you have to return it to the caller (or use a global/package variable, but you should avoid that).

    You can call it wherever you have a reference to it.

Re: calling from outside the closure a sub defined in a closure
by siva kumar (Pilgrim) on Sep 19, 2007 at 09:30 UTC
    You can't. You can use if the subroutine in local scope.
    { local $subRef = sub { $var = shift; print "hello monks --- [$var] \n"; }; &callFun(); } sub callFun { &$subRef(20); }
    OR
    { $subRef = sub { $var = shift; print "hello monks --- [$var] \n"; }; } &$subRef;