如何跳转到Perl中的特定输入行?

时间:2008-12-11 17:37:50

标签: perl loops

我想跳到第一行包含“include”。

<> until /include/;

为什么这不起作用?

2 个答案:

答案 0 :(得分:10)

匹配运算符默认使用$_,但默认情况下<>运算符不存储到$_,除非它在while循环中使用,因此$_中没有存储任何内容1}}。

来自perldoc perlop

   I/O Operators
   ...

   Ordinarily you must assign the returned value to a variable, but there
   is one situation where an automatic assignment happens.  If and only if
   the input symbol is the only thing inside the conditional of a "while"
   statement (even if disguised as a "for(;;)" loop), the value is auto‐
   matically assigned to the global variable $_, destroying whatever was
   there previously.  (This may seem like an odd thing to you, but you’ll
   use the construct in almost every Perl script you write.)  The $_ vari‐
   able is not implicitly localized.  You’ll have to put a "local $_;"
   before the loop if you want that to happen.

   The following lines are equivalent:

       while (defined($_ = )) { print; }
       while ($_ = ) { print; }
       while () { print; }
       for (;;) { print; }
       print while defined($_ = );
       print while ($_ = );
       print while ;

   This also behaves similarly, but avoids $_ :

       while (my $line = ) { print $line }

答案 1 :(得分:4)

<>只是while(<>)构造中的魔法。否则,它不会分配给$_,因此/include/正则表达式无法匹配。如果你用-w运行它,Perl会告诉你:

Use of uninitialized value in pattern match (m//) at ....

您可以使用以下方法解决此问题:

$_ = <> until /include/;

要避免警告:

while(<>)
{
    last if /include/;
}
豫ICP备18024241号-1