Yes, very possible. Say that you have your names, one per line, in
names.txt. You can read them into an array then use
join to join the array members into a string separated by the pipe symbol ('|') which is the alternation metacharacter in a regex. Thus your pattern reads match Fred or Joe or ... or Pete. Like this.
use strict;
use warnings;
my $namesFile = q{names.txt};
open my $namesFH, q{<}, $namesFile
or die qq{open: $namesFile: $!\n};
my @names = <$namesFH>;
close $namesFH
or die qq{close: $namesFile: $!\n};
chomp @names; # Remove line terminators
my $namesPatt = join q{|}, @names;
my $dataFile = q{data.txt};
open my $dataFH, q{<}, $dataFile
or die qq{open: $dataFile: $!\n};
while ( <$dataFH> )
{
print qq{Found name $1\n} if /($namesPatt)/;
}
close $dataFH
or die qq{close: $dataFile: $!\n};
Note that I use parentheses in the regex to capture the name matched for later use in $1. I hope this is helpful.
Cheers,
JohnGG
Update: Corrected poor punctuation/grammar.
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: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.