加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

Perl逐行读取

发布时间:2020-12-15 21:28:05 所属栏目:大数据 来源:网络整理
导读:我有一个简单的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
我有一个简单的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);

解决方法

如果你使用严格打开,你会发现$ 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;
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读