I'm writing this because I lost about 1-2 hours to debug a problem which was caused by closures.

Suppose you have a method of a class that you write using Moose(but a plain Perl object is also relevant), and you use inside that method a static variable (static in the C sense, by that I mean a variable that has scope local to the method but a lifetime that spans each call of said method). I was recommended that I use a closure and enclose the declaration of that variable and the method inside the closure to cause the variable to be static(again, the C sense of static).

What happened, was that when I created 2 objects, the value of that static variable wasn't really resetted, so most of my tests started failing, so of course the next natural move(after debugging for 1-2 hours) was to either

I chose the latter.

Please notice that the former would attract another problem: suppose you were doing this not inside a class, but inside a role, which does not define the ctor/dtor , so now you can't reset it in the ctor/dtor because that is not specific to the role, it's specific to classes consuming that role.

I suspect there are at least 2 plausible reasons for this :

I will be cautious not to draw any conclusions from this, instead, I'd like your oppinion on closures and their side-effects.


In reply to Some trouble with closures by spx2

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.