Starfish Starfish - 2 months ago 13
Perl Question

Multiple pattern match using smartmatch (AND condition)

I came across the following multi pattern matching using smartmatch operator:

smartmatch

In the answers section, Brad explains multiple pattern matching using smartwatch for logical OR across matching patterns.

How can I use smartmatch to return 1 only if all the patterns match i.e. Logical AND?

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.

Comments