Tôi muốn bỏ qua dòng đầu tiên có chứa "bao gồm".Làm cách nào để bỏ qua một dòng nhập cụ thể trong Perl?
<> until /include/;
Tại sao tính năng này không hoạt động?
Tôi muốn bỏ qua dòng đầu tiên có chứa "bao gồm".Làm cách nào để bỏ qua một dòng nhập cụ thể trong Perl?
<> until /include/;
Tại sao tính năng này không hoạt động?
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 }
<>
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/;
}
thực sự? Tôi không ý kiến. thanks – user44511
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
Nó chỉ là một phím tắt để bạn có thể nói "while (<>) {...}" thay vì "while (defined ($ _ = <>)) {...}". –