joshywashy has asked for the wisdom of the Perl Monks concerning the following question:

I have an if expression in which I am trying to match multiple strings using the || operator. I would like to reuse my IF statement to search for other sets of strings. What is the proper way to store these sets of strings? I have something like this:

if( /sdfsd/||/abc/||/def/||/hijk/ ) {.....}

I would like to turn it into something like this:

$a = /sdfsd/||/abc/||/def/||/hijk/; $b = /qqqq/||/ff/||/wqeoir/; if ($a) {...}

Replies are listed 'Best First'.
Re: Storing pattern matches
by ww (Archbishop) on Jan 04, 2014 at 02:23 UTC
    Not positive I've understood your question correctly, but are you looking for something like this?
    #!/usr/bin/perl use 5.016; use warnings; # 1069225 save match templates for reuse? my $regex = qr/(sdfsd|abc|def|hijk)/; say "\t regex is: $regex\n"; my @string = ('xyzalmnopdef', 'sdfsd', 'hijk lmn op', 'babcdefijk2345', 'xaybz3', ); for my $string(@string) { if ( $string =~ /($regex)/g ) { # /g only if you expect to # find more than one match per li +ne say "got a match in $string: $1"; }else{ say "\t No match found in $string"; } }
    Execution:
    C:\>1069225.pl regex is: (?^u:(sdfsd|abc|def|hijk)) got a match in xyzalmnopdef: def got a match in sdfsd: sdfsd got a match in hijk lmn op: hijk got a match in babcdefijk2345: abc No match found in xaybz3 C:\>

    At the worst, perhaps this offers some help.

    Update/PS: Failed to explain the /g. Fixed with comment in code.

    If I've misconstrued your question or the logic needed to answer it, I offer my apologies to all those electrons which were inconvenienced by the creation of this post.
Re: Storing pattern matches
by davido (Cardinal) on Jan 04, 2014 at 02:44 UTC

    The qr// operator, described in perlop is used to create regexp objects that can be used later on. This is essentially compiling and storing the regular expression. The regexp object can either be interpolated into a larger expression, or used by itself. For example:

    my $bobs = qr/(?:\b(?:[Bb]ob|[Rr]obert)\b)/; my $franks = qr/(?:\b[Ff]ran(?:k(?:lin)?|cis)\b)/; my $string = 'Franklin'; print "He's here!\n" if $string =~ m/$bobs|$franks/; print "Bob is too!\n" if "Bob" =~ $bobs;

    Dave

Re: Storing pattern matches
by NetWallah (Canon) on Jan 04, 2014 at 01:17 UTC
    Consider using the Alternation metacharacter (|), in the regular expression (perldoc perlre).

    You may also need to use "non-capturing parentheses (?:).

            If your eyes hurt after you drink coffee, you have to take the spoon out of the cup.
                  -Norm Crosby

Re: Storing pattern matches
by basiliscos (Pilgrim) on Jan 04, 2014 at 10:33 UTC
    May be you should look at Regexp::Grammars. It allows to parse relatively complex texts in declarative way.
Re: Storing pattern matches
by Anonymous Monk on Jan 04, 2014 at 03:38 UTC

    In that case you are halfway there.