in reply to Sparing multiple 'or's

TIMTOWTDI, but here are two methods (grep and regex) to get you started:

#!/usr/bin/env perl use strict; use warnings; my @cases = qw/ABA SCO ACC PHC GHF/; my $re = join '|', @cases; for my $text ('SCO', 'Microsoft') { print "$text found (grep)\n" if grep {$text eq $_} @cases; print "$text found (regex)\n" if $text =~ /^$re$/; }

PS. It would be better not to use $a as a variable name since that is special with respect to sorting.

Replies are listed 'Best First'.
Re^2: Sparing multiple 'or's
by AnomalousMonk (Archbishop) on Jun 04, 2018 at 16:28 UTC

    Note that the results for the examples of the two methods differ:

    c:\@Work\Perl\monks>perl -wMstrict -le "my @cases = qw/ABA SCO ACC PHC GHF/; my $re = join '|', @cases; ;; for my $text ('SCO', 'ENDOSCOPE', 'Microsoft') { print qq{'$text' found (grep)} if grep { $text eq $_ } @cases; print qq{'$text' found (regex)} if $text =~ /^$re$/; } " 'SCO' found (grep) 'SCO' found (regex) 'ENDOSCOPE' found (regex)
    See haukex's Building Regex Alternations Dynamically.


    Give a man a fish:  <%-{-{-{-<

      Good catch (++). As dave_the_m suggested we can use brackets in this case:

      #!/usr/bin/env perl use strict; use warnings; use utf8; my @cases = qw/ABA SCO ACC PHC GHF/; my $re = join '|', @cases; for my $text ('SCO', 'ENDOSCOPE', 'Microsoft') { print "$text found (grep)\n" if grep {$text eq $_} @cases; print "$text found (regex)\n" if $text =~ /^($re)$/; }