MSG said:
According to Perl Cookbook, the three dots (...) should be
"not inclusive" while the two dots (..) "inclusive" when used
with line numbers. By "not inclusive", I would think that the
code below will print only line 2, but it prints the same first
three lines just like using (..). Can someone please explain?
I don't have my copy of the Cookbook on me, so I don't know in what
context "inclusive" is used. However, `perldoc perlop` explains it
thusly:
Each ".." operator maintains its own boolean
state. It is false as long as its left operand is false.
Once the left operand is true, the range operator stays true
until the right operand is true, AFTER which the range
operator becomes false again. It doesn't become false till
the next time the range operator is evaluated. It can test
the right operand and become false on the same evaluation it
became true (as in awk), but it still returns true once. If
you don't want it to test the right operand till the next
evaluation, as in sed, just use three dots ("...") instead
of two.
So the difference is that with .., the right operand is evaluated on
the same iteration that the left became true. With ..., it's not
evaluated until the next time around. So to illustrate, based on your
example:
#!/usr/bin/env perl
use strict;
use warnings;
while ( <DATA> ){
if ( 2 .. 2 ){
print "A: $_";
}
if ( 2 ... 2 ){
print "B: $_";
}
}
__DATA__
Line 1
Line 2
Line 3
Line 4
Output:
A: Line 2
B: Line 2
B: Line 3
B: Line 4
(This is all much clearer if you keep in mind that the expressions are
actually shorthand for
$. == 2 .. $. == 2
and
$. == 2 ... $. == 2
respectively)
So, in the first one, the left hand argument evaluated to true, which
made the expression true. But in that same iteration, the right-hand
argument became true, which made the expression true on the *next*
iteration. So only one line was printed.
In the second one, the left hand argument evaluated to true, making the
expression true. And that was it. In the next iteration, $. == 2 was
false, so the right argument remained false, and the overall expression
remained true for the remainder of the loop.
Does that help to explain it at all?
Paul Lalli