2008-12-11 51 views

回答

10

匹配操作符默認使用$_但除非它是在一個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 } 
+0

真的嗎?我不知道。謝謝 – user44511 2008-12-11 17:47:15

4

<>僅在while(<>)構造神奇。否則,它不會分配給$_,所以/include/正則表達式沒有任何可匹配的內容。如果你跑這跟-w的Perl會告訴你:

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

你可以解決這個問題:

$_ = <> until /include/; 

爲了避免警告:

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