m/$keyword/
is wrong. You need to escape special characters. A simple way of doing this is
m/\Q$keyword/
my $pattern = join('|', @keywords );
has the same problem. Use
my $pattern = join('|', map quotemeta, @keywords);
instead.
If the list of words is long, you can speed things up a lot by using Regexp::List:
my $pattern = Regexp::List->new->list2re(@keywords);
All together, we get:
use Regexp::List (); my @keywords = ("keyword1", "keyword2", "keyword3"); my $pattern = Regexp::List->new->list2re(@keywords); #my $pattern = join('|', map quotemeta, @keywords); # Alternative while (<SEARCHFILE>) { if ($_ =~ $pattern) { # or just: if (/$pattern/) { print $_; # or just: print; } }
In reply to Re^2: searching for keywords
by ikegami
in thread searching for keywords
by Anonymous Monk
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |