如何确定单词在文本中出现的次数?

kam*_*aci 0 regex perl text file

如何在Perl中找到单词在文本块中的次数?

例如我的文本文件是这样的:

#! /usr/bin/perl -w
# The 'terrible' program - a poorly formatted 'oddeven'.
use constant HOWMANY => 4; $count = 0;
while ( $count < HOWMANY ) {
  $count++;
  if ( $count == 1 ) {
    print "odd\n"; 
  } elsif ( $count == 2 ) { 
    print "even\n";
  } elsif ( $count == 3 ) {
    print "odd\n";
  } else { # at this point $count is four.
    print "even\n";
  }
}  
Run Code Online (Sandbox Code Playgroud)

我想找到该文本文件的"count"字数.文件名为terrible.pl

理想情况下,它应该使用正则表达式最少的代码行.

编辑:这是我尝试过的:

use IO::File;
my $fh = IO::File->new('terrible.pl', 'r') or die "$!\n";
my %words;
while (<$fh>) {
  for my $word ($text =~ /count/g) {
  print "x";
    $words{$word}++;
  }
}
print $words{$word};
Run Code Online (Sandbox Code Playgroud)

LHM*_*ies 6

这是一个完整的解决方案.如果这是家庭作业,你可以通过向老师解释这一点来学习更多内容,而不是自己动手:

perl -0777ne "print+(@@=/count/g)+0" terrible.pl
Run Code Online (Sandbox Code Playgroud)