2008-12-11 11 views

cevap

10

maç operatörü $_ kullanarak varsayılan ama hiçbir şey $_ saklanan ediliyor yüzden bir süre döngüde kullanılmadığı sürece <> operatör varsayılan olarak $_ içine saklamaz. perldoc perlop itibaren

:

 
    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

:

$_ = <> until /include/; 

uyarı önlemek için? Hiç bir fikrim yoktu. teşekkürler – user44511

+0

Ben de. Bir süre içinde olmadığında <> neden farklı davranıyor? – Kip

+0

Sadece bir kısayol, böylece "while (defined ($ _ = <>)) {...}" yerine while (<>) {...} "diyebilirsiniz. –

4

<> bir while(<>) yapıda sadece bir büyüdür. Aksi halde, $_'a atanmaz, bu nedenle /include/ düzenli ifadenin karşı eşleşecek hiçbir şeyi yoktur. Eğer -w ile bu çalıştırdıysanız Perl söylerdim:

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

Sen ile bu sorunu giderebilirsiniz: gerçekten

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