Take the 2-minute tour ×

I have an array

my @array = qw/FOO BAR BAZ/;

and a scalar read from a file containing data like




I am looking for a nice way to check if an element of the array matches part of the input string.

I know I could just loop over the array and match that way but was wondering if there is a more perl like way.

share|improve this question
regular expression? yes? –  gaussblurinc Jul 24 '13 at 8:32
do{if($str=~m/$_/){print "YES!"; print; print "\n"}} for @array –  gaussblurinc Jul 24 '13 at 8:33
@loldop, OP did say that they preferred a way that does not involve looping over an array. –  S.R.I Jul 24 '13 at 8:40
@S.R.I, thank you, I miss it –  gaussblurinc Jul 24 '13 at 8:42
add comment

3 Answers

up vote 4 down vote accepted

You can create a regex that matches all of the @array:

my $regex = join '|', map quotemeta, @array;
$string =~ $regex;
share|improve this answer
add comment

Yes, there is far better way. You can construct regular expression. It will be alternatives of fixed strings which is fortunately translated into trie (Aho-Corasick) which leads into linear search time. It is the most efficient way at all.

my @array = qw/FOO BAR BAZ/;
my $re = join '|', map quotemeta, @array;
$re = qr/$re/;

for my $string (@strings) {
  if ($string =~ $re) {
share|improve this answer
add comment

That is exactly what grep is for. Here's a small snippet:

use strict;
use warnings;

my $str = "+++123++585+++FOO";
my $blank = "+++123++585+++XYZ";
my @array = qw/FOO BAR BAZ/;
print grep {$str =~ $_} @array, "\n";
print grep {$blank =~ $_} @array, "\n";

This would just return:


grep, reduce and map are what we call higher order functions in FP world, though reduce might be called fold there. Have a look at MJD's Higher Order Perl for more of these.

share|improve this answer
grep, map, and reduce imply a loop that is quite unneccessary here, although your knowledge of HOP is laudable. –  amon Jul 24 '13 at 11:35
While I agree that grep, map and reduce are essentially loop iterations under the hood, I can see how my solution is less than optimal. That said, OP did want a solution that looked more perlish. I'll let this answer be as a reminder to give considered answers and not halfbaked ones. –  S.R.I Jul 24 '13 at 12:49
add comment

Your Answer


