my @nums = ('1203', '1204', '1207');
my $regex = '\b(?:' + join('|', @nums) + ')\b';
No way is provided for if (my ($match) = m/$regex/) { ... } to capture anything (and thus be true). Also, only a single match per line is assumed. (Also + (addition) is used where . (concatenation) is intended.)
I would suggest something along the lines of
c:\@Work\Perl\monks>perl -wMstrict -MData::Dump -le
"my @nums = ('1203', '1204', '1207');
my $regex = '\b(?:' . join('|', @nums) . ')\b';
print qq{'$regex'};
;;
my @matches = 'w 1207 x 1203 y 9999 z' =~ m{ $regex }xmsg;
dd \@matches;
"
'\b(?:1203|1204|1207)\b'
[1207, 1203]
with the loop being (also
untested):
while ( <$file_h> ) {
if (my @matches = m/$regex/g) {
++$matched{$_} for @matches;
print "$file $_";
}
}
Update: Changed code example to include 9999 group.
Update 2: Shorter, IMHO sweeter:
c:\@Work\Perl\monks>perl -wMstrict -MData::Dump -le
"my @nums = qw(1203 1204 1207 1111);
my ($regex) = map qr{ \b (?: $_) \b }xms, join ' | ', @nums;
print $regex;
;;
my %seen;
for ('w 1207 x 1203 y 9999 z',
'w 11203 x 12033 y 112033 z',
'w 1207 x 1203 y 9999 z 1207 zz',
) {
print qq{>$_<} if map ++$seen{$_}, m{ $regex }xmsg;
}
dd \%seen;
;;
my $not_seen = join ' ', grep !$seen{$_}, @nums;
print 'num(s) not seen: ', $not_seen || '(none)';
"
(?msx-i: \b (?: 1203 | 1204 | 1207 | 1111) \b )
>w 1207 x 1203 y 9999 z<
>w 1207 x 1203 y 9999 z 1207 zz<
{ 1203 => 2, 1207 => 3 }
num(s) not seen: 1204 1111
Give a man a fish: <%-{-{-{-<
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.