字符串匹配和Text::Match::FastAlternatives



我需要找到Perl中大量长字符串中大量短字符串的所有出现。就像

my $count = () = $bigstr =~ /$smallstr/g

由于正则表达式需要花费大量时间,所以我研究了字符串匹配算法并找到了Perl模块Text::Match::FastAlternatives。在文档中,它只说这个模块可以用来查找一个字符串是否在另一个字符串中找到。但是有没有一种方法来计算Text::Match::FastAlternatives出现的次数呢?希望如此。

当您必须每次都重新解析正则表达式时,是的,这需要时间。

我会建议Benchmarking不同的解决方案,但加快速度的一种方法是缓存您打算在匿名子例程中匹配的所有字符串。

类似下面的伪代码:

use strict;
use warnings;
my @short_strings = (...);
my @long_strings = (...);
my @match_subs = map {
    my $code = "sub { return scalar(() = shift =~ /Q$_E/g }";
    my $sub = eval $code;
    die "Unable to cache sub $code: $@" if $@;
    $sub
} @short_strings;
for my $data (@long_strings) {
    my $count;
    $count += $_->($data) for @match_subs;
    print $count;
}

最新更新