我有一个简单的 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 http://perldoc.perl.org/perlvar.html)
如果您想使用计数器,请使用
my $count = 0;
while( my $line = <$info>) {
print $line;
last if ++$count == 2;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)