in reply to Re: for loops and 'and'
in thread for loops and 'and'

No, this demo defeats what you said: (BTW, just for people who does not know, $. is not the line number of your script, but the line input number of last accessed handler. In the demo, the running line number of __DATA__)

use strict; use warnings; my $s = "1..11"; <DATA> for (1..5); print for (1..10 or $s); <DATA> for (1..7); print for (1..10 or $s); __DATA__ 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15

This code prints 1..11 twice.

Replies are listed 'Best First'.
Re: Re: Re: for loops and 'and'
by ysth (Canon) on Nov 30, 2003 at 20:27 UTC
    No, this demo defeats what you said
    I'm not sure which part you are responding to. I assume you understand this code, but for others I will point out that the <DATA> for (1..5) leaves $. set to 5 and then <DATA> for (1..7) makes it 12. For neither 1..10 is it equal to 1, so the flipflop returns false.

      Hm... I don't comment what you said, as I am not sure whether I actually have understood what you said as it meant to be. Any way, try those two pieces, and hope they mean something to you (no harm, food for thought :-):

      use strict; use warnings; my $s = "1..11"; while (my $line = <DATA>) { print "line = $line"; print for (1..10 or $s); print "\n"; } __DATA__ 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15

      And this:

      use strict; use warnings; my $s = "1..11"; <DATA>; print for (1..10 or $s); print "\n"; <DATA>; print for (1..10 or $s); print "\n"; <DATA>; print for (1..10 or $s); print "\n"; <DATA>; print for (1..10 or $s); print "\n"; <DATA>; print for (1..10 or $s); print "\n"; <DATA>; print for (1..10 or $s); print "\n"; <DATA>; print for (1..10 or $s); print "\n"; <DATA>; print for (1..10 or $s); print "\n"; <DATA>; print for (1..10 or $s); print "\n"; <DATA>; print for (1..10 or $s); print "\n"; <DATA>; print for (1..10 or $s); print "\n"; <DATA>; print for (1..10 or $s); print "\n"; __DATA__ 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
        To explain why the two differ (where the second is just an unwrapped loop, pretty much otherwise equivalent to the first):

        Each flipflop operator has its own independent hidden state variable in the pad. It acts like a my $flipflopstate at the top of the enclosing sub or file, only a different variable for each flipflop in the sub/file.

        Thus, in your second example, the first 1..10 gets set true (because $. is 1) but none of the later ones are (because they never pass the beginning check for $.==1).

        In the first example, the flipflop returns true 10 times because it meets the $.==1 check the first time and doesn't meet the $.==10 check until the 10th time.

        Note that because the hidden state acts like sub-scoped lexical, a recursive call to the sub will start with a fresh state, and ditto multiple threads in the same sub.