我有一个简单的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);
Run Code Online (Sandbox Code Playgroud)
fri*_*edo 120
如果你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;
Run Code Online (Sandbox Code Playgroud)
这利用了特殊变量$.,该变量跟踪当前文件中的行号.(见perlvar)
如果您想使用计数器,请使用
my $count = 0;
while( my $line = <$info>) {
print $line;
last if ++$count == 2;
}
Run Code Online (Sandbox Code Playgroud)
Eva*_*oll 12
使用这些类型的复杂程序,最好让Perl为您生成Perl代码:
$ perl -MO=Deparse -pe'exit if $.>2'
Run Code Online (Sandbox Code Playgroud)
哪位高兴地告诉你答案,
LINE: while (defined($_ = <ARGV>)) {
exit if $. > 2;
}
continue {
die "-p destination: $!\n" unless print $_;
}
Run Code Online (Sandbox Code Playgroud)
或者,您可以从命令行简单地运行它,
$ perl -pe'exit if$.>2' file.txt
Run Code Online (Sandbox Code Playgroud)
你需要使用++$counter,而不是 $++counter因为它不工作的原因..
| 归档时间: |
|
| 查看次数: |
275389 次 |
| 最近记录: |