Perl 逐行读取

标签 perl

我有一个简单的 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/

相关文章:

Perl Tkx, "button"和 "ttk__button"之间有什么区别?

linux - Perl 不返回 PID

perl - 在 perl 脚本中使用环境变量

perl - 我如何进行模式匹配并继续写入新文件直到另一个模式匹配

perl - 在 Perl 中,如何区分 JSON 编码中的数字和字符串哈希值?

linux - 用于捕获在反引号中执行的命令的 stderr 和 stdout 的 Perl 脚本

linux - Perl - 自动将用户名和密码添加到 Linux 系统的脚本

multithreading - Perl服务器中的内存泄漏

perl - 什么时候应该使用子程序属性?

Excel::Writer::XLSX 写入未格式化的日期