On Saturday 04 December 2004 06:15 pm, Alexey Trofimenko wrote:
> oh! that it. I've found example which could make it clear to me
>
> sub test {
>    return sub {
>      for 1..3 {
>         state $var = 1;
>         print $var++
>      }
>    }
> }
>
> $a = test; $a() for 1..3; print ';'
> $b = test; $b() for 1..3;
>
> that could print, for different possible definitions of "state":
> 1) 123123123;123123123
> 2) 123456789;123456789
> 3) 123456789;101112131415161718
>
> looks like you meant third(!) variant.. but it doesn't make any sense for
> me.

The idea is that $var's _visibility_ is tied to scoping: it's only accessible 
inside that set of braces, like a lexical. But its lifetime is like a package 
variable. It's initialized once, and then it lives its life in peace. As 
Larry said, you could emulate it by having a package variable and 
lexicalizing it with "our", but if you're only going to use it as a state 
variable, then why have it be potentially visible to the rest of the world? 
So "state" gives you a variable with a permanent lifetime, but lexical scope. 
It seems too simple to be wrong, to me :)

--hobbs

Reply via email to