Filtering a lines from a list of keywords

I have massive log files from which I want to filter out lines containing phrases out of a list. So, I have put the words in an array and for every line, I have to go through a foreach loop.
 
Something like
my @phrases = ( 'phrase1', 'phrase2', 'phraseN');

while(<$filehandle>)
{
    foreach my $phrase (@phrases)
   {
        print if (/$phrase/);
    }
}
       
However this is very slow.  Any way I could make it fast?
LVL 31
farzanjAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

ozoCommented:
one way may be to precompile the matches

$_  = qr/$_/ for @phrases;

another way may be to combine the the phrases into a single search
my $phrase = qr/@{[join'|',@phrases]}/;
but then you would only print once if there are multiple matches, so you may also want to change the print to
print for /$phrase/g
0
ozoCommented:
$phrase = qr/@{[join'|',@phrases]}/
may need to be modified if any of the phrases contain metacharacters
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
ozoCommented:
see also
perldoc -q "How do I efficiently match many regular expressions at once"
0
farzanjAuthor Commented:
Hi Ozo,  this is really great.  However, I have a confusion.  I am trying to benchmark both the methods and the results were different.  As I printed the search strings, there appears
(?-xism:
In front of my phrases -- once in each the phrase in $_  = qr/$_/ for @phrases; method and only once in the second method like
(?-xism:phrase1|phrase2|phrase3...

Please guide.
0
farzanjAuthor Commented:
Thanks for all the help.
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Perl

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.