firoz
firoz

Reputation: 91

pattern match in whole array

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

Answers (3)

Toto
Toto

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

Miller
Miller

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

Lee Duhem
Lee Duhem

Reputation: 15121

You could try something like

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

Upvotes: 1

Related Questions