如何从字符串数组中找到模式

时间:2019-07-18 14:37:53

标签: perl pattern-matching

如何找到可以定义一组字符串的模式? 例如,如果我有这些字符串

my @single = (
  "Hello World my name is Alice",
  "Hello World my name is Bob",
  "Hello World my name is Charlie"
);

my @multi = (
  "That Building is very small",
  "That Ladder is very tall"
);

我目前尝试的是将句子与确切数量的单词分成几组。然后在节点是单词的地方构建一棵树,如果节点有很多分支,它们将被*代替。但这仅在*末尾(@single)时有效,而在*末尾(@multi)时则无效

基本上,我要输出的模式是输入为字符串数组的模式。给定上面的字符串,如何在下面生成这些模式?

my $single_pattern = "Hello World my name is *"
my $multi_pattern = "That * is very *"

1 个答案:

答案 0 :(得分:1)

use 5.010;
use Perl6::Junction qw(all);

sub pattern_from_wordset {
    my (@wordset) = @_;
    my @transposed;
    for my $string (@wordset) {
        my @parts = split / /, $string;
        while (my ($index, $part) = each @parts) {
            push $transposed[$index]->@*, $part;
        }
    }
    my @pattern;
    for my $words (@transposed) {
        push @pattern, (all($words->@*) eq $words->[0])
            ? $words->[0]
            : '*';
    }
    return @pattern;
}

my @single = …
my @multi = …

say join ' ', pattern_from_wordset @single;
say join ' ', pattern_from_wordset @multi;
__END__
Hello World my name is *
That * is very *