tags:

views:

142

answers:

2

Say I have the string "i zipped the fezz and it blipped like a baa" and I have an array of words (moo, baa, zip, fjezz, blaa) that I wanted to test to see it they're contained in the string, is there a way of doing so without either using | in the regex or iterating over each word?

TIA

+6  A: 

If you're using Perl 5.10, you can use the smart match operator:

my @words = qw/moo bar zip fjezz blaa/;
if ( @words ~~ $str ) { 
    # it's there
}

The above will do an equality check (equivalent to grep $_ eq $str, @words). If you want a regex match, you can use

if ( @words ~~ /$str/ )

Otherwise, you're stuck with grep or first from List::Util:

if ( grep { $str =~ /$_/ } @words ) { 
    ...
}
friedo
`grep { $str =~ /$_/ } @words` should be `grep { $_ =~ /$str/ } @words`
Kinopiko
Can you still extract matches when using grep? i.e. if (grep { $str =~ /(\d+)($_)/ } @words) { found "1: $1\n2: $2\n"; }A quick try doesn't seem to work.
Sparkles
@Sparkles where did the `\d+` come from?
Sinan Ünür
@Sparles and what would expect `$1` and `$2` to hold once `grep` is finished checking the match against every element of `@words`?
Sinan Ünür
draegtun
A: 

Given your desire to extract the matches as you indicate in a comment to @friedo's answer, I am confused as to why you want to avoid alternation:

use strict; use warnings;

use Regex::PreSuf;

my $str = 'i zipped the fezz and it blipped like a baa';

my $re = presuf(qw(moo baa zip fjezz blaa));

my @matches = $str =~ /($re)/g;

print "@matches\n";

Output:

zip baa

Or, do you want the words in the original sentence that match?

use strict; use warnings;

use Regex::PreSuf;

my $re = presuf(qw(moo baa zip fjezz blaa));

my $str = 'i zipped the fezz and it blipped like a baa';

my @matches = grep { /$re/ } split /\s+/, $str;

print "@matches\n";

Output:

zipped baa
Sinan Ünür
Regex::PreSuf shouldn't be used (except perhaps for very long lists) on 5.10 and above; the built-in trie processing is much faster.
ysth