我有一个简单的Perl脚本逐行读取文件。代码如下。我想显示两行并打破循环。但它不工作。 bug在哪里?
$file='SnPmaster.txt';
open(INFO,$file) or die("Could not open file.");
$count = 0;
foreach $line (<INFO>) {
print $line;
if ($++counter == 2){
last;
}
}
close(INFO);
解决方法
如果你使用严格打开,你会发现$ foo没有任何意义。
以下是操作方法:
use strict;
use warnings;
my $file = 'SnPmaster.txt';
open my $info,$file or die "Could not open $file: $!";
while( my $line = <$info>) {
print $line;
last if $. == 2;
}
close $info;
这利用了特殊变量$。它跟踪当前文件中的行号。 (见perlvar)
如果要使用计数器,请使用
my $count = 0;
while( my $line = <$info>) {
print $line;
last if ++$count == 2;
}
