Perl 逐行读取 [英] Perl read line by line

查看:38
本文介绍了Perl 逐行读取的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的 Perl 脚本来逐行读取文件.代码如下.我想显示两行并打破循环.但它不起作用.错误在哪里?

I have a simple Perl script to read a file line by line. Code is below. I want to display two lines and break the loop. But it doesn't work. Where is the 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);

推荐答案

如果你打开了 use strict,你会发现 $++foo没有任何意义.

If you had use strict turned on, you would have found out that $++foo doesn't make any sense.

方法如下:

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)

This takes advantage of the special variable $. which keeps track of the line number in the current file. (See perlvar)

如果您想改用计数器,请使用

If you want to use a counter instead, use

my $count = 0;
while( my $line = <$info>)  {   
    print $line;    
    last if ++$count == 2;
}

这篇关于Perl 逐行读取的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆