I second moritz. You've created a persistent state variable -- a static variable in your terms -- a variable local to the class, not to the instance. Therefore, it's not reset on object creation, which is exactly what you want if you want a persistent state.

You probably don't want that, if you want it to be reset for each object; you just want an ordinary attribute -- a variable local to the instance. The traditional choice is to declare the object in the constructor as a reference to a blessed hash and store your data within the hash. There are other ways to do it, of course.

Um, by the way, if you do decide to create a persistent state variable, you might want to enclose the entire class in braces, rather than only one method:

THIS: package Foo; { my $state = 0; # better initialize it sub new {...}; sub fiddle {...}; sub faddle {...}; sub fuddle {...}; } __END__ NOT THAT: package Foo; sub new {...}; sub fiddle {...}; { my $state = 0; # better initialize it sub faddle {...}; } sub fuddle {...}; __END__

If you do THIS, then when you $bar = Foo::new(); and later $bar->fiddle() or $bar->fuddle() it, you will still have access within those methods to $state. If you don't, and do THAT (as you described), then you will have created a state variable peculiar to the method faddle(), invisible even to other methods of the same class. Are you sure y/N?


In reply to Re^2: Some trouble with closures by Xiong
in thread 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.