输出出现字符串的行号

时间:2018-09-13 12:48:04

标签: file perl text

我正在尝试确定字符串TableView在文本文件中出现多少次以及出现在哪些行中。

该脚本输出的行号不正确,而是连续输出数字(1,2,..),而不是该单词的正确行。

file.txt

{{ collection.metafields.NAMESPACE.KEY }}

目标输出

Apples

相反,如下面的代码所示,我的输出是:

    Apples
    Grapes
    Oranges
    Apples

Perl

Apples appear 2 times in this file
Apples appear on these lines: 1, 4,

1 个答案:

答案 0 :(得分:5)

您的代码存在许多问题,但是行号打印错误的原因是,每次$counter出现在一行中后,您就递增变量Apples并将其保存到@lineAry。这与出现字符串的行数不同,最简单的解决方法是使用内置变量$.,该变量表示对文件句柄执行读取的次数

此外,我鼓励您使用词汇文件句柄和open的三参数形式,并检查对open的每次调用是否成功

您永远不会使用$initialLine的值,而且我不明白您为什么将其初始化为10

我会这样写

use strict;
use warnings 'all';

my $filename = 'file.txt';

open my $fh, '<', $filename or die qq{Unable to open "$filename" for input: $!};

my @lines;
my $n;

while ( <$fh> ) {
    push @lines, $. if /apples/i;
    ++$n while /apples/ig;
}

print "Apples appear $n times in this file\n";
print "Apples appear on these lines: ", join( ', ', @lines ), "\n\n";

输出

Apples appear 2 times in this file
Apples appear on these lines: 1, 4