Reputation: 1221
I am checking a regex pattern against each line of STDIN foreach value in an array. I am using the value in the array in the regex pattern. So the example below should match any row that has one of the three numbers in @nums followed by 6 more digits.
my @nums = qw/
509
544
555
/;
while(my $line = <>) {
chomp $line;
foreach my $num (@nums) {
if ($line =~ /$num\d{6}/) {
say $line;
}
}
}
input
504333322
544009113
509323232
1509868333333
443123432
509999
5599234
410987655
output
544009113
509323232
1509868333333
This is working fine for me, but I would like to know, in order to increase performance, if there is way to do the same thing without the repeated regex matching.
Thank You.
Upvotes: 0
Views: 283
Reputation: 6204
The following--a variation of TLP's in a comment above--creates a positive lookbehind of alternations using the values in @nums
:
use strict;
use warnings;
my @nums = qw/
509
544
555
/;
my $ORnums = '(?<=' . ( join '|', @nums ) . ')';
my $regex = qr/$ORnums\d{6}/;
while (<DATA>) {
print if /$regex/;
}
__DATA__
504333322
544009113
509323232
1509868333333
443123432
509999
5599234
410987655
Output:
544009113
509323232
1509868333333
Hope this helps!
Upvotes: 2