匹配文件中的sting并计算总出现次数

时间:2016-02-27 07:21:39

标签: perl file

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

search.txt

play       dream
dream      play
dream

keyword.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);


    }
}

但它计算的总出现次数为5

1 个答案:

答案 0 :(得分:0)

您可以使用哈希来计算单词出现次数。关键字作为哈希的关键并计为值。

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

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