Perl脚本 - 令人困惑的错误

时间:2016-02-13 16:24:46

标签: perl

当我运行此代码时,我纯粹是试图让所有包含单词""在他们中。听起来很容易。但是当我运行它时,我得到一个包含单词&#34的匹配列表;"但只在最后一行。我不知道它为什么会这样出来,我一直在努力解决它。我目前得到总共268个输出的输出,我需要的输出只有13.请指教!

#!/usr/bin/perl -w
#Usage: conc.shift.pl textfile word

open (FH, "$ARGV[0]") || die "cannot open";
@array = (1,2,3,4,5);
$count = 0;
while($line = <FH>) {
    chomp $line;
    shift @array;
    push(@array, $line);
    $count++;
    if ($line =~ /that/)
    {
        $output = join(" ",@array);
        print "$output \n";
    }
}

print "Total matches: $count\n";

1 个答案:

答案 0 :(得分:2)

只有当该行包含“that”,时,您才想增加$count变量:

if ($line =~ /that/) {
  $count++;

而不是在之前递增计数器,而不是检查$line是否包含“那个”,就像你拥有它一样:

$count++;
if ($line =~ /that/) {

同样,我怀疑用于存储push()中匹配行的join()@array调用也应位于if块内,仅在$ boxes -h boxes - draws any kind of box around your text (and removes it) (c) Thomas Jensen <boxes@thomasjensen.com> Web page: http://boxes.thomasjensen.com/ Usage: boxes [options] [infile [outfile]] -a fmt alignment/positioning of text inside box [default: hlvt] -c str use single shape box design where str is the W shape -d name box design [default: first one in file] -f file configuration file -h print usage information -i mode indentation mode [default: box] -k bool leading/trailing blank line retention on removal -l list available box designs w/ samples -m mend box, i.e. remove it and redraw it afterwards -p fmt padding [default: none] -r remove box -s wxh box size (width w and/or height h) -t str tab stop distance and expansion [default: 8e] -v print version information 块内执行line包含“that”。

希望这有帮助!