2008-12-11 28 views

Trả lời

10

Toán tử đối sánh mặc định bằng cách sử dụng $_ nhưng toán tử <> không lưu trữ thành $_ theo mặc định trừ khi được sử dụng trong một vòng lặp while nên không có gì được lưu trữ trong $_.

Từ 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

thực sự? Tôi không ý kiến. thanks – user44511

+0

Tôi cũng vậy. Tại sao <> hoạt động khác khi nó không ở trong một vòng lặp while? – Kip

+0

Nó chỉ là một phím tắt để bạn có thể nói "while (<>) {...}" thay vì "while (defined ($ _ = <>)) {...}". –

4

<> chỉ kỳ diệu trong một cấu trúc while(<>). Nếu không, nó sẽ không gán cho $_, do đó, biểu thức chính quy /include/ không có gì khớp với nhau. Nếu bạn chạy này với -w Perl sẽ cho bạn biết:

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

Bạn có thể sửa lỗi này với:

$_ = <> until /include/; 

Để tránh các cảnh báo:

while(<>) 
{ 
    last if /include/; 
} 
Các vấn đề liên quan