我有一个简单的 Perl 脚本来逐行读取文件。代码如下。我想显示两行并打破循环。但这不起作用。错误在哪里?
$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);
最佳答案
如果您启用了 use strict
,您会发现 $++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;
}
关于Perl 逐行读取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4505381/