develooper Front page | perl.perl6.language | Postings from August 2001

Re: explicitly declare closures???

Thread Previous | Thread Next
Dave Mitchell
August 22, 2001 09:10
Re: explicitly declare closures???
Message ID:
John Porter <> 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.

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

    sub new_counter_pair {
	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();
show_counters(); # should print "1,2"

Thread Previous | Thread Next Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at | Group listing | About