On Sun, Dec 05, 2004 at 02:15:51AM +0300, Alexey Trofimenko wrote:
: I thought, its primary use is for closures:
: 
:   sub test {
:     my $a=10;
:     return sub { $a++ }
:   }
: 
: vs
:   sub test {
:     return sub {state $a=10; $a++ }
:   }
: 
: $func1 = test;
: $func2 = test;
: 
: would closures in $func1 and $func2 share the SAME $a?

No, they're separate.

: or is it that "function cloning" you said?

Yes, except it'd be better to call it "closure cloning".

: 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.

I don't know how you even get the third variant.  I think it should be 2,
though I see how you'd get 1 if you think a loop clones every time through.
Certainly that one doesn't, since it doesn't refer to any external lexicals.
Perhaps statehood should be limited to "official" subs just like "return" is.

Larry

Reply via email to