简体   繁体   English

Perl Flip Flop运算符和行号

[英]Perl Flip Flop operator and line numbers

I noticed this while looking at another question ... 我在看另一个问题时注意到了这一点......

If I have a script like this: 如果我有这样的脚本:

while (<>) {
  print if 5 .. undef;
}

It skips lines 1..4 then prints the rest of the file. 它会跳过第1..4行,然后打印文件的其余部分。 However if I try this: 但是如果我试试这个:

my $start_line = 5;
while (<>) {
  print if $start_line .. undef;
}

It prints from line 1. Can anyone explain why? 它从第1行打印。任何人都可以解释原因吗?

Actually I'm not even sure why the first one works. 实际上我甚至不确定为什么第一个有效。

Hmmm looking further into this I found that this works: 嗯,进一步研究这个我发现这有效:

my $start = 5;
while (<>) {
  print if $. ==  $start .. undef;
}

So the first version magically uses $. 所以第一个版本神奇地使用了$. which is the line number. 这是行号。 But I don't know why it fails with a variable. 但我不知道为什么它失败了变量。

The use of a bare number in the flip-flop is treated as a test against the line count variable, $. 在触发器中使用裸号被视为对行计数变量$. . From perldoc perlop : 来自perldoc perlop

If either operand of scalar ".." is a constant expression , that operand is considered true if it is equal ( == ) to the current input line number (the $. variable). 如果标量".."任一操作数是常量表达式 ,则如果该操作数与当前输入行号( $.变量)相等( == ),则该操作数被视为true。

So 所以

print if 5 .. undef;

is "shorthand" for: 是“速记”:

print if $. == 5 .. undef;

The same is not true for a scalar variable as it is not a constant expression. 对于标量变量,情况并非如此,因为它不是常量表达式。 This is why it is not tested against $. 这就是它没有针对$.进行测试的原因$. .

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM