On Sat, 4 Dec 2004 22:03:19 -0800, Larry Wall <[EMAIL PROTECTED]> wrote:

On Sun, Dec 05, 2004 at 02:15:51AM +0300, 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.


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.

third variant is what we get if we replace C<state> with perl5 "my $var if 0" here (not exactly, because $var start value would be undef in that case).


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.

they must be limited. It would be really strange if

  sub test {
     for 1..3 {
        state $var = 1;
        print $var++
     }
  }
  test();test();

and

  sub test {
     my $a;
     for 1..3 {
        do_something_with($a);
        state $var = 1;
        print $var++
     }
  }
  test();test();

would print different results.

But actually I would prefer if state somehow could be made to work other way, even if closure isn't cloned. I mean, first variant, mentioned at top of the message. Then we could use state vars in things like:

  # I know that _this_ particular task could be solved better
  # I'm not good in examplification.

  %hash = map {state $k=1; $_ => $k++ } @array;

and always get our keys numbered from 1. And one still get behaviour(2) if state declaration is at start of subroutine.
(Hmm, but I can't figure if it is possible )


This applies to FIRST {...} blocks too.

for 1..10 {
  for 1..3 {
    FIRST {...}
    ...
  }
}

I'd expect that FIRST would be fired 10 times, not only once, because FIRST looks here just as a mere funny loop control structure.
and of course I don't want it to happen once here, and 10 times there, depending on such a subtle thing as appearance of outer lexical variables in inner block. hmm.. but I don't want unnecessary cloning either, if it'd slow down my program. I have a cake, please show me where to bite:)

Reply via email to