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,
returns a new coderef each time it run, each with it's own instance of count.sub xcmp { my $count; $x = sub { return $count }; return $x; }
Whereas
returns a coderef, but it's always the same coderef, carrying aroun the same instance of $count. --Bob Niederman, http://bob-n.comsub xcmp { my $count; sub get_count { return $count } return &get_count; }
In reply to Re: Re: Closures and sort
by bobn
in thread Closures and sort
by traveler
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |