我正在尝试确定字符串TableView
在文本文件中出现多少次以及出现在哪些行中。
该脚本输出的行号不正确,而是连续输出数字(1,2,..),而不是该单词的正确行。
{{ collection.metafields.NAMESPACE.KEY }}
Apples
相反,如下面的代码所示,我的输出是:
Apples
Grapes
Oranges
Apples
Apples appear 2 times in this file
Apples appear on these lines: 1, 4,
答案 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