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

如何在Perl中跳到特定的输入行?,perl,loops,Perl,Loops,我想跳到包含“include”的第一行 until/include/; 为什么不起作用?匹配操作符默认使用$\u,但是操作符默认不存储到$\u中,除非它在while循环中使用,所以$\u中没有存储任何内容 从perldoc perlop: I/O Operators ... Ordinarily you must assign the returned value to a variable, but there is one situation where an auto

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

until/include/;

为什么不起作用?

匹配操作符默认使用
$\u
,但是
操作符默认不存储到
$\u
中,除非它在while循环中使用,所以
$\u
中没有存储任何内容

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 } I/O操作员 ... 通常必须将返回值赋给变量,但是 是发生自动分配的一种情况。当且仅当 输入符号是“while”条件中的唯一内容 语句(即使伪装为“for(;)”循环),该值也是自动的 自动分配给全局变量$\ux,销毁所有 以前有。(这对你来说可能是件奇怪的事,但你会 几乎在您编写的每一个Perl脚本中都使用该构造。)the$\uVari‐ able不是隐式本地化的。您必须输入“本地美元” 在循环之前,如果你想让它发生的话。 以下几行是等效的: 而(已定义($=){print;} 而($=){print;} while(){print;} 对于(;){print;} 定义时打印($=); 边打印边打印($); 边打印边打印; 这也具有类似的行为,但避免了$\ 而(my$line=){print$line}
while()
构造中唯一的魔法。否则,它不会分配给
$\uuu
,因此
/include/
正则表达式没有可匹配的内容。如果您使用
-w
运行此程序,Perl将告诉您:

Use of uninitialized value in pattern match (m//) at ....
您可以通过以下方法解决此问题:

$_ = <> until /include/;
$\=until/include/;
要避免警告,请执行以下操作:

while(<>)
{
    last if /include/;
}
while()
{
最后如果/包括/;
}

我也是。为什么当它不在while循环中时会有不同的行为呢?它只是一个快捷方式,您可以说“while(){…}”,而不是“while(defined($){…}”)。
while(<>)
{
    last if /include/;
}