in reply to Re^2: Catching closures
in thread Catching closures

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.

Replies are listed 'Best First'.
Re^4: Catching closures
by hipowls (Curate) on Mar 06, 2008 at 10:09 UTC

    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.