in reply to Re: Catching closures
in thread Catching closures

I also don't see the problem. If the subroutine refers to lexicals in the enclosing scope and modifies them, no harm is done since it gets its own copy of the lexicals

You could equally well say that assignment can have bad effects and be hard to track down.

Replies are listed 'Best First'.
Re^3: Catching closures
by akho (Hermit) on Mar 05, 2008 at 21:21 UTC
    Well, technically it doesn't get its own copy, it shares its copy with stuff declared in the same scope:

    use strict; use warnings; sub funcs { my $a = 0; return ( sub { $a++ }, sub { $a } ); } my ( $f11, $f12 ) = funcs(); my ( $f21, $f22 ) = funcs(); print join( " ", $f11->(), $f12->(), $f22->() ), "\n"; #prints "0 1 0"

    My point was that if someone wants to change state, he should understand what he's doing. And he probably does. Preventing that is rude.

    The OP may be in some special situation, however. That's what my question was about.

      I guess to be really pedantic that should be it shares a copy with stuff declared in the same scope at the same time.but functions declared on entering the same scope later get their own set of shared variables. I take your point though and stand corrected.

      I read CountZero's reply and I now understand the OP's concern but I don't see that debugging a variable that has leaked into a closure is any harder than debugging the same problem with regular functions.

      my $var; sub the_first { $var = func1(); } # many, many lines of code later sub the_second { $var = disfunction(); }
      and in most cases the closures are declared together so it is probably easier to spot.

      I think the answer is to be careful with variables, restricting them to as small a scope as possible and to have as few as possible with file scope.