in reply to Re^3: Bolt on where a match is not found to a print script
in thread Bolt on where a match is not found to a print script

my $regex = '\b(' + join('|', @nums) + ')\b';

Still the whole addition/concatenation problem.

Also, moving the capture into  $regex doesn't address multiple captures per line. This may not even be a possibility in the OPer's application (nothing is ever said about this), but I like to defend against things like this.


Give a man a fish:  <%-{-{-{-<

Replies are listed 'Best First'.
Re^5: Bolt on where a match is not found to a print script
by QM (Parson) on Dec 06, 2017 at 12:07 UTC
    Does this fix it?
    for my $m (m/$regex/g) { # Update: reworked $matched{$m} = 1; print "$file $_"; }

    Full code:

    #!/usr/bin/env perl use strict; use warnings; my @files = <c:/perl64/myfiles/*>; # record matching regexes our %matched; my @nums = ('1203', '1204', '1207'); my $regex = '\b(' . join('|', @nums) . ')\b'; # update: fixed + to . for my $file ( @files ) { open my $file_h, '<', $file or die "Can't open $file: $!"; while ( <$file_h> ) { for my $m (m/$regex/g) { # Update: reworked $matched{$m} = 1; print "$file $_"; } } } # Check all nums have been seen for my $num (@nums) { if (not exists($matched{$num})) { print "$num not found\n"; } }

    -QM
    --
    Quantum Mechanics: The dreams stuff is made of

      What Anonymous Monk said:

      while (my ($match) = m/$regex/g) { $matched{$match} = 1; print "$file $_"; }
      gives you an infinite loop.
      c:\@Work\Perl\monks>perl -wMstrict -le "my $regex = qr{ \b f[eio]e \b }xms; ;; $_ = 'xx fee fie foe yy'; while (m/($regex)/g) { my $match = $1; print qq{captured '$match'}; } " captured 'fee' captured 'fie' captured 'foe'
      works better (at least it stops). If you want to get a bit fancy,
      while (m/($regex)/g and my $match = $1) { print qq{captured '$match'}; }
      also works. But the whole "extract multiple matches per line" thing may not even be a real issue! The OPer says nothing about it, and I only raised it as a cautionary point of interest.


      Give a man a fish:  <%-{-{-{-<

      Fixed original.

      -QM
      --
      Quantum Mechanics: The dreams stuff is made of

      this matches, but loops infinitly on the same line print, the script never finishes