in reply to Some trouble with closures

I'm a bit confused by your confusion.

If you want to store data that's not shared between different instances (objects) of the same class, an attribute is what you need, and what attributes are there for.

Your description that you don't want the variable shared between various objects indicates that a static variable (emulated by a lexical variable from an outer scope, or implemented by a state variable) is specifically not what you need.

I can recommend a very good book to you: Bertrand Meyer, Object-Oriented Software Construction. If you read that from cover to cover, I can guarantee that you won't confuse attributes with anything else afterwards.

closures cause various side-effects not immediately noticeable that lead to bugs

Every construct leads to bugs when used in a context where it's not appropriate.

Perl 6 - links to (nearly) everything that is Perl 6.

Replies are listed 'Best First'.
Re^2: Some trouble with closures
by Xiong (Hermit) on Feb 17, 2010 at 15:23 UTC

    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:

    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?