代码之家  ›  专栏  ›  技术社区  ›  user44511

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

  •  5
  • user44511  · 技术社区  · 17 年前

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

    <> until /include/;
    

    为什么这不起作用?

    2 回复  |  直到 17 年前
        1
  •  10
  •   Robert Gamble    17 年前

    匹配运算符默认为使用 $_ 但是 <> 操作员不存储到 美元 默认情况下,除非它在while循环中使用,否则不会在其中存储任何内容 美元 .

    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 }
    
        2
  •  4
  •   brian d foy    17 年前

    <> 是唯一的魔法 while(<>) 构建。否则它不会分配给 $_ 所以 /include/ 正则表达式没有可匹配的内容。如果你用 -w Perl会告诉你:

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

    您可以使用以下方法修复此问题:

    $_ = <> until /include/;
    

    要避免警告:

    while(<>)
    {
        last if /include/;
    }