我试图确定字符串Apples出现在文本文件中的时间以及出现的行数.
脚本输出的行号不正确,而是连续输出数字(1,2,..),而不是单词的正确行.
Apples
Grapes
Oranges
Apples
Run Code Online (Sandbox Code Playgroud)
Apples appear 2 times in this file
Apples appear on these lines: 1, 4,
Run Code Online (Sandbox Code Playgroud)
相反,我的输出如下面的代码所示:
Apples appear 2 times in this file
Apples appear on these lines: 1, 2,
Run Code Online (Sandbox Code Playgroud)
my $filename = "<file.txt";
open( TEXT, $filename );
$initialLine = 10; ## holds the number of the line
$line = 0;
$counter = 0;
# holder for line numbers
@lineAry = ();
while ( $line = <TEXT> ) {
chomp( $line );
if ( $line =~ /Apples/ ) {
while ( $line =~ /Apples/ig ) {
$counter++;
}
push( @lineAry, $counter );
$initialLine++;
}
}
close( TEXT );
# print "\n\n'Apples' occurs $counter times in file.\n";
print "Apples appear $counter times in this file\n";
print "Apples appear on these lines: ";
foreach $a ( @lineAry ) {
print "$a, ";
}
print "\n\n";
exit;
Run Code Online (Sandbox Code Playgroud)
您的代码存在许多问题,但错误地打印行号的原因是,$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";
Run Code Online (Sandbox Code Playgroud)
Apples appear 2 times in this file
Apples appear on these lines: 1, 4
Run Code Online (Sandbox Code Playgroud)