Starfish Starfish - 2 months ago 7
Perl Question

How can I check that a string matches all patterns in an array using smartmatch?

I want to check that a string matches multiple regex patterns. I came across a related question, which Brad Gilbert answered using the smartmatch operator:

my @matches = (
qr/.*\.so$/,
qr/.*_mdb\.v$/,
qr/.*daidir/,
qr/\.__solver_cache__/,
qr/csrc/,
qr/csrc\.vmc/,
qr/gensimv/,
);

if( $_ ~~ @matches ){
...
}


The
if
statement is entered if any of the patterns match, but I want to check that all of the patterns match. How can I do this?

Answer

The smartmatch operator does not support that. You'll have to build it yourself. List::MoreUtils' all seems great to do that.

use strict;
use warnings 'all';
use feature 'say';
use List::MoreUtils 'all';

my @matches = (
    qr/foo/,
    qr/ooo/,
    qr/bar/,
    qr/asdf/,
);

my $string = 'fooooobar';
say $string if all { $string =~ $_ } @matches;

This gives no output.

If you change $string to 'fooooobarasdf' it will output the string.