Reputation: 91
Could anyone please tell me how to search a pattern in whole array at once eg
@array = ('I am AA','I am BB', 'I am CC', 'I am AAC')
$pattern = "AA"
I am using following logic but it is not working
if (@array =~ /$pattern/) {
# do this;
} else {
# do that
}
Thanks
Upvotes: 0
Views: 68
Reputation: 91518
You could use the 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";
}
Upvotes: 1
Reputation: 35218
You're likely looking for a 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
}
However, it is also possible that your pattern will not necessarily work the way that you expect if this is anything like what you're actually matching. I'd advise that you add a word boundary to your pattern and also quotemeta
.
if (my @matches = grep {$_ =~ /\b\Q$pattern\E\b/} @array) {
Upvotes: 5
Reputation: 15121
You could try something like
if (grep m/$pattern/, @array) {
# do something
}
else {
# do other things
}
Upvotes: 1