The syntax error is because you don't have a block for your 'if' statement, only for the 'while'. You could get by without the block if you turned it into a modifier (see perlsyn), as follows:

print $_ if( $_ =~ m/$keyword/ );

There's more to it than that, though, because you're using the assignment operator ('=', see perlop) in what appears to be a pattern match, hence the modification I made to your code in the above example. If @keywords is large, use Super Search to find examples of using an array in a pattern match. If it is reasonably small, you can use alternation (perlre):

my $pattern = join( '|', @keywords ); if( $_ =~ m/$pattern/ )

Oh, and in addition to using strict and warnings, you may also find diagnostics helpful.

HTH

ikegami is absolutely right about escaping special characters, of course (see quotemeta). Thanks and ++ for pointing that out!

Update: full code example, with escaped characters

use strict; use warnings; my @keywords = qw( keyword1 keyword2 keyword3 ); my $pattern = join( '|', map quotemeta, @keywords ); print "pattern = [$pattern]\n"; # using 'if' as a modifier while( my $line = <DATA> ) { print $line if ( $line =~ m/$pattern/ ); } # using an 'if' block while( my $line = <DATA> ) { if( $line =~ m/$pattern/ ) { print $line; } } __DATA__ somelines... somelines... somewords...keyword1..somewords somelines... somewords... keyword2...somewords...

Both examples print:

pattern = [keyword1|keyword2|keyword3] somewords...keyword1..somewords keyword2...somewords...


In reply to Re: searching for keywords by bobf
in thread searching for keywords by Anonymous Monk

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.