in reply to Mathching an array in regex
When you put an array into a string or regex literal, it gets expanded to join($", @arr) (/cool guy here/ in this case.)
One rather good solution is:
my @arr = qw( cool guy here ); my $str = "I am cool"; my $re = "(?:" . (join '|', map quotemeta, @arr) . ")"; if ($str =~ $re) { # if ($str =~ /^$re$/) { print "Matched\n"; # print "Equals\n"; } # }
I used quotemeta because I presumed your array holds strings and not regexs.
If your array contains many elements and you want a bit more speed, you could use Regexp::List.
use Regexp::List qw( ); my @arr = qw( cool guy here ); my $str = "I am cool"; my $re = Regexp::List->new(@arr)->list2re(); if ($str =~ $re) { # if ($str =~ /^$re$/) { print "Matched\n"; # print "Equals\n"; } # }
Regexp::List accepts a list of text. If you had a list of regexps, you'd use Regexp::Assemble instead.
Of course, you could avoid regexs entirely.
my @arr = qw( cool guy here ); my $str = "I am cool"; if (grep {index($str,$_)!=-1} @arr) { # if (grep {$str eq $_} @arr) { print "Matched\n"; # print "Equals\n"; } # }
Update: Added johngg's version for symetry. Originally, I only had the "Equals" version for grep.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Mathching an array in regex
by johngg (Canon) on Oct 12, 2007 at 12:38 UTC |