gr0bz
gr0bz

Reputation: 189

Search if a string matches with any regex of an array in Perl

I have an array containing some PCRE matching patterns (like "prefix_.*") and I'm comparing a string with all the patterns of the array. Currently, I'm working with this code:

foreach (@matchingPatterns) {
    if ("$string" =~ "$_") {
        [do something]
    }
}

This code is working well but I'm sure that there is a prettier way to do that in Perl (without any loop?).

Am I wrong? ;)

Upvotes: 0

Views: 135

Answers (1)

Sean
Sean

Reputation: 29800

There's not much scope for improvement here, but I'd be more liable to write something like one of the following:

for (@matchingPatterns) {
    next if $string !~ /$_/;
    # do something
}

or

for (grep { $string =~ /$_/ } @matchingPatterns) {
    # do something
}

...both of which at least save you a few lines of code.

Upvotes: 1

Related Questions