【问题标题】:perl line count a file containing a specific textperl 行计数包含特定文本的文件
【发布时间】:2013-07-17 07:26:28
【问题描述】:

基本上我想计算包含单词 Out 的行数。

my $lc1 = 0;
open my $file, "<", "LNP_Define.cfg" or die($!);
#return [ grep m|Out|, <$file> ]; (I tried something with return to but also failed)
#$lc1++ while <$file>;
#while <$file> {$lc1++ if (the idea of the if statement is to count lines if it contains  Out)
close $file;
print $lc1, "\n";

【问题讨论】:

    标签: perl parameters line-count


    【解决方案1】:

    命令行也可能是您的潜在选择:

    perl -ne '$lc1++ if /Out/; END { print "$lc1\n"; } ' LNP_Define.cfg
    

    -nEND 之前为您的所有代码假定一个 while 循环。
    -e 需要由 ' ' 包围的代码。

    $lc1++ 仅在以下 if 语句为真时才计数。

    if 语句每行运行一次以查找“Out”。

    END { } 语句用于while 循环结束后的处理。您可以在此处打印计数。

    或者不用命令行:

    my $lc1;
    while ( readline ) {
        $lc1++ if /Out/; 
    }    
    print "$lc1\n";
    

    然后在命令行运行:

    $ perl count.pl LNP_Define.cfg
    

    【讨论】:

      【解决方案2】:

      使用index:

      0 <= index $_, 'Out' and $lc1++ while <$file>;
      

      【讨论】:

      • 我个人会更喜欢括号括起来的索引参数,相比之下前面的0
      • choroba 你能解释一下这条线在做什么吗?谢谢。
      • @dsaliba:它在每一行中搜索“Out”。如果在某处找到它(index 返回位置,即 0 或更多),则 $lc1 递增。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-03-05
      • 1970-01-01
      • 2017-11-29
      • 1970-01-01
      • 2018-03-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多