John Porter <[EMAIL PROTECTED]> wrote:
> Dave Mitchell wrote:
> > I think closures are a lot harder (or at least subtler) than people
> > think, 
> 
> It's hard for me to agree with you, because I've never had *any*
> problems with closures. (And yes, I use them all the time.)
> The scenario you gave seems rather far-fetched to me, in terms
> of real-world programming.

Perhaps, although the following code demonstrates it, and isn't (too)
contrived. Comment out the 'superfluous' "$counters[$i] = 0;" line and
the code stops working. Anyway, I suspect we'll have to agree to disagree :-)

Dave M.


#!./perl
{
    my @counters;   # private lexicals shared by the 2 subs,
    my $index = -1; # but not visible elsewhere

    sub new_counter_pair {
        $index++;
        my $i = $index; # create private snapshot of index
        $counters[$i] = 0;
        return sub {$counters[$i]++}, sub {$counters[$i]--};
    }

    sub show_counters {
        print join(',', @counters), "\n";
    }
}

my ($inc0, $dec0) = new_counter_pair();
my ($inc1, $dec1) = new_counter_pair();
$inc0->();
$inc0->();
$dec0->();
$inc1->();
$inc1->();
show_counters(); # should print "1,2"




Reply via email to