2008-12-11 6 views

Antwort

10

Die Match-Operator standardmäßig $_ verwenden, aber der <> Operator speichert nicht in $_ standardmäßig, wenn es in einer while-Schleife verwendet wird, so wird nichts in $_ gespeichert werden.

Von 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

wirklich? ich hatte keine Ahnung. danke – user44511

+0

Ich auch nicht. Warum verhält sich <> anders, wenn es sich nicht in einer While-Schleife befindet? – Kip

+0

Es ist nur eine Abkürzung, so dass Sie "while (<>) {...}" anstelle von "while (definiert ($ _ = <>)) {...}" sagen können. –

4

<> ist Magie in einem while(<>) Konstrukt. Ansonsten wird es nicht $_ zugeordnet, so dass der /include/ reguläre Ausdruck nichts dagegen hat. Wenn Sie dies mit -w lief Perl würde Ihnen sagen:

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

Sie können dieses Problem beheben, mit:

$_ = <> until /include/; 

die Warnung zu vermeiden:

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