Perl 匹配文件中的sting并计算发生的总数

Perl 匹配文件中的sting并计算发生的总数,perl,file,Perl,File,我有两个文件,一个是关键字文件,另一个是搜索文件 search.txt play dream dream play dream 关键字.txt play dream 我想计算玩耍和做梦的总次数,例如play=2,dream=3 到目前为止,我尝试的代码是: #!usr/bin/perl use strict; use warnings; #Lexical variable for filehandle is preferred, and always error ch

我有两个文件,一个是关键字文件,另一个是搜索文件

search.txt

play       dream
dream      play
dream
关键字.txt

play
dream
我想计算玩耍和做梦的总次数,例如
play=2,dream=3

到目前为止,我尝试的代码是:

#!usr/bin/perl
use strict;
use warnings;

#Lexical variable for filehandle is preferred, and always error check opens.
open my $keywords,    '<', 'keyword.txt' or die "Can't open keywords: $!";
open my $search_file, '<', 'search.txt'   or die "Can't open search file: $!";
my $count=0;
my $keyword_or = join '|', map {chomp;qr/\Q$_\E/} <$keywords>;
my $regex = qr|\b($keyword_or)\b|;

while (<$search_file>)
{

    while (/$regex/g)
    {
    $count++;
        print "$.: $1\n";
        print($count);


    }
}
#!usr/bin/perl
严格使用;
使用警告;
#首选filehandle的词法变量,并始终打开错误检查。

打开我的$keywords,你可以使用散列来计算单词出现的次数。关键字作为散列的键,计数作为值

while (/$regex/g){
    $hash{$1}++;
}

# print the hash    
foreach(keys %hash){
    print "$_ : $hash{$_}\n";
}

使用逗号和句号。请不要有两个文件,一个是有如梦想和发挥关键字,而另一个是有梦想和发挥多行。我们需要的是从第1个文件中获取关键字,并在otherso play=2和dream=3中查找关键字出现的总数。这应该是预期的输出
%
是用于在Perl中声明哈希的sigil。散列是Perl中的数据类型,有关更多信息,请查看