|Do you know where your variables are?|
Re^2: How will you use state declared variables in Perl6?by Limbic~Region (Chancellor)
|on Jul 08, 2005 at 21:51 UTC||Need Help??|
Globals are trouble, no matter how you label them. Closures are much safer.
I am sure that neither you nor I have any confusion as to how state variables in Perl6 will work, but I want to respond to this as I think it may lead others astray. A variable's visibility declared with state is still restricted to the scope it was declared in. The difference from a regular lexicals is that if program execution comes back to that scope the variable is not re-initizalized and its previous value is restored. Update: TimToady has explained it much better.
In your example, foo() is a global sub, so there can never be two instances of it, but if foo() was a method, multiple instances of whatever class foo() was a method of, would all share the same %seen. Effectively, %seen becomes a Class variable. These can be useful--eg. counting the number of instances created or in existiance--but why not use a Class variable instead?
You are correct - variables declared with state can be used to simulate class variables just as the example I provided shows. In that case, OO didn't exist yet. Unlike p5, methods and subs will be very distinguishable in Perl6. That should make it easier to distinguish when it is more appropriate to use a class variable - but caution is warranted.
However, not having a similar possibility to control which handle, setting applied to $/ and $\ will affect, is worse. The separation and encapsulation of state is what makes OO so useful.
This is fixed in Perl6.
If P6 objects are going to be usable across threads, then using state varibles for singletons is going to produce potential problems where, for example, DB handles can only be used from one thread.
The bulk of your reply seems to be focused on how state declared variables may cause problems with OO. Nothing in my post indicated that's how I thought they should be used other than to say if you don't have OO yet - they make simulating it easier. The example I gave was that of a regular sub - not a method. I asked for examples of how others might use it. From your reply, I can assume you won't be using it for OO. Can you think of any other places you might use it for?
Cheers - L~R