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

In reply to Re: Re: Closures and sort by bobn
in thread Closures and sort by traveler

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.