2008-12-11 28 views

Respuesta

10

Los valores predeterminados del operador partido a la utilización de $_ pero el operador <> no almacena en $_ por defecto a menos que se utiliza en un bucle while para que nada se almacena en $_.

De 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

realmente? no tenía ni idea. gracias – user44511

+0

Yo tampoco. ¿Por qué <> se comporta de manera diferente cuando no está en un ciclo while? – Kip

+0

Es solo un atajo para que pueda decir "while (<>) {...}" en lugar de "while (defined ($ _ = <>) {...}". –

4

<> es única magia en una construcción de while(<>). De lo contrario, no se asigna a $_, por lo que la expresión regular /include/ no tiene nada que hacer. Si ejecutó esto con -w Perl le diría:

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

Puedes solucionar este problema con:

$_ = <> until /include/; 

Para evitar la advertencia:

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