2

我在看另一个问题时注意到了这一点......

如果我有这样的脚本:

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

它跳过第 1..4 行,然后打印文件的其余部分。但是,如果我尝试这个:

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

它从第 1 行打印。谁能解释为什么?

实际上我什至不确定为什么第一个有效。

嗯,进一步研究我发现这有效:

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

所以第一个版本神奇地使用$.了行号。但我不知道为什么它会因变量而失败。

4

1 回答 1

10

The use of a bare number in the flip-flop is treated as a test against the line count variable, $.. From 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).

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 $..

于 2014-06-08T11:37:11.407 回答