in reply to Closures and sort

I took larsen's advice but did the following. I still cannot get the count to reset before the second sort. Why doesn't calling xcmp the second time reset count?
use strict; $|=1; my @list = qw/ box cow dog apple ant/; sub xcmp{ my $count = 0; sub get_count { return $count } # an inspector as a closure # and another closure sub compare { $count++; return $_[0] cmp $_[1]; } return(\&compare, \&get_count); } my @funcs = xcmp(); print sort { $funcs[0]( $a, $b ) } @list; print "\n"; print $funcs[1](), "\n"; @funcs = xcmp(); print sort { $funcs[0]( $a, $b ) } @list; print "\n"; print $funcs[1](), "\n";
--traveler

Replies are listed 'Best First'.
Re: Re: Closures and sort
by bobn (Chaplain) on Aug 05, 2003 at 02:36 UTC

    Because your sub get_count {} and sub compare {} are run once, at compile time, no matter how many times you call xcmp. So the subroutines are the same each time, even after callin xcmp in between. TO show this, do a print $funcs[1](), "\n"; after the first and second callst to xcmp() - they're the same. If you look at Re: Re: Re: Closures and sort and add a print "$compare\n"; after each call to mksubs(), you'll see these are different.

    So your functions continue to carry around the same instance of $count, but, each time xcmp is run, it is a new instance of $count which is being set to zero.

    Looked at another way,

    sub xcmp { my $count; $x = sub { return $count }; return $x; }
    returns a new coderef each time it run, each with it's own instance of count.

    Whereas

    sub xcmp { my $count; sub get_count { return $count } return &get_count; }
    returns a coderef, but it's always the same coderef, carrying aroun the same instance of $count.

    --Bob Niederman, http://bob-n.com