整个数组中的模式匹配

时间:2014-04-10 06:12:31

标签: perl pattern-matching

有人可以告诉我如何一次搜索整个阵列中的模式 例如

@array = ('I am AA','I am BB', 'I am CC', 'I am AAC')
$pattern = "AA"

我正在使用以下逻辑,但它无法正常工作

if (@array =~ /$pattern/) {
    # do this; 
} else {
    # do that 
} 

由于

3 个答案:

答案 0 :(得分:5)

您可能正在寻找grep

my @array = ('I am AA','I am BB', 'I am CC', 'I am AAC');
my $pattern = "AA";

if (my @matches = grep {$_ =~ /$pattern/} @array) {
    print "These entries matched:\n";
    print "'$_'\n" for @matches;
    # do this; 

} else {
    # do that 
} 

但是,如果您的模式与您实际匹配的模式类似,那么您的模式也可能无法按预期方式运行。我建议您为模板添加单词边界,并quotemeta

if (my @matches = grep {$_ =~ /\b\Q$pattern\E\b/} @array) {

答案 1 :(得分:1)

您可以尝试类似

的内容
if (grep m/$pattern/, @array) {
    # do something
}
else {
    # do other things
}

答案 2 :(得分:1)

您可以使用smart match operator

my @array = ('I am AA','I am BB', 'I am CC', 'I am AAC');
my $pattern = qr"AA";

if ($pattern ~~ @array) {
    say "Found"; 
} else {
    say "NOT found"; 
}