in reply to Re: Some trouble with closures
in thread Some trouble with closures

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?