- 论坛徽章:
- 0
|
Perl Range Operator
in a list context, this operator is easy to use and understand: .. return a list of values counting (by ones) from the left value to the right value. This is useful for wrting for (1 .. 10) loops and for doing slice operations on arrays:
@foo = @foo[-5 .. -1]; #slice last 5 items.
#!/usr/bin/perl
foreach (1..100)
{
print;
}
foreach (A..B)
{
print;
}
It is much more confusing in a scalar context. Let's look at the simplest cases first and then move to the more difficult:
#!/usr/bin/perl
while(<>)
{
print "$. $_" if 3 .. 10;
}
That prints lines 3 to 10 of any input of file given to it. if we change it to print "$. $_" if 3 ... 10; it works the same way. But we aren't limited to line numbers. Let's create a file "g":
# stuff
# stuff
# end on same line as start
START foo END
#
# end by itself
END
# more stuff
# more stuff
# another start
START
# and more stuff
END
# trailing stuff
and a perl script to read it:
#!/usr/bin/perl
while(<>)
{
print if(/START/../END/);
}
Running that against our file produces:
START foo END
START
# and more stuff
END
But with the three dot version:
#!/usr/bin/perl
while(<>)
{
print if(/START/.../END/);
}
the results are different:
START foo END
#
# end by itself
END
START
# and more stuff
END
The difference is how the operator treats its left side and right side when they appear on the same line or out of order.Here's what's going on: with the two dot ".." version, the operator returns false until the left hand side is true. It then switches to returnning true and keeps doing that until its right hand expression evaluates to true. But the operator $EMAINS true until the next evaluation even so, so it only switches back to false when the next line is read. with the three dot "..." version, the right hand expression will not evaluated while the left hand is false, and vice versa. Confusing? you bet .. be very careful when using these opeartors and test your logic against sample input very carefully.
本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/emili/archive/2010/02/20/5312998.aspx |
|