in reply to Closures and undefined subs

I think your problem is that you've misunderstood the scope of local. As soon as your out subroutine's scope is exited both of in and in2 are restored to their previous contents.

I'm not following exactly why you're trying to do this from your sample code, but I think what you'd want is to store the coderefs in lexically scoped scalars and call things using the arrow syntax rather than mucking about with local and what not.

sub out { my $x = shift; my $in = sub { ... }; my $in2 = sub { ...; my $rs = $in->( $arg ); ... }; return $x + $in_2->( ); }

Replies are listed 'Best First'.
Re^2: Closures and undefined subs
by ikegami (Patriarch) on Sep 26, 2007 at 14:27 UTC

    As soon as your out subroutine's scope is exited both of in and in2 are restored to their previous contents.

    That's not a problem since he doesn't create any external references to in_2. He'd need lexicals in that case. For example, he'd need to use lexicals if the outer sub returned \&in_2.

    Using lexicals doesn't help here. In addition to the more complex call syntax, using lexicals would create a memory leak if recursion was involved unless you explicitly undefed the lexical at the end of the outer sub.

      I am afraid use solved my problem but I am not happy for that :-)
      RungeKutta needs \&in_2 in its own call.
      I my opinion I need to write the closures as Rungekutta needs some equation in the differentiation sub. In this case the equation is too complex and needs variables that are imported into the outer sub of the package. So I guess I am in need of that much levels of complexity.
      But what do you mean with lexicals? Could you give a "simple" example? Thank you.

        But what do you mean with lexicals? Could you give a "simple" example? Thank you.

        Short for "lexical variables".

        my $var;

        RungeKutta needs \&in_2 in its own call.

        Not a problem. See the solution I added to my original post in this thread.

      I disagree (which doesn't mean I'm right :-) - the code is parsed with the rest of the file; all refs to that code will be to the same piece. Lexicals FTW!
Re^2: Closures and undefined subs
by Anonymous Monk on Sep 26, 2007 at 14:30 UTC
    Thank you for your replay but as I use the strict pragma and I wont disable it your solution will not work.
    But nevertheless I guess you are right. Rungekutta uses the sub several times and local is not the right thing to use in this case.
    What else could you suggest in order to make the inner subs using the vars from the outer one.
      You've done something wrong if you need to turn off strict. Fletch's code works fine with strict. And the inner subs have no problems using the variables in the outer one. Could you show us your code?