I want to apply a set of regex on each line of this file
At the risk of tiring readers with yet another plug for my module, I'll point out that it offers a "tracked pattern" mode, whereby you can assemble your array of regexps into a single pattern, which gives you the efficiency of performing a single match, and the convenience of being able to determine which, of the original expressions, was the one that matched. The code would go something like:
use strict; use Regexp::Assemble; my $re = Regexp::Assemble->new( track => 1 ); open IN, shift || 'patterns' or die "open pattern file: $!\n"; while( <IN> ) { chomp; $re->add($_); } close IN; # read from, e.g., STDIN while( <> ) { chomp; if( defined( my $match = $re->match($_)) ) { print " $_ matched by $match\n"; } }
What is not obvious, is that behind the scenes, the $re->match() is performing a single match. It is not looping over the entire list of patterns. It has to be this way (rather than using the more intuitive if( /$re/ ) {...}) because of current broken behaviour in the regular expression engine (see bug #32840 for details).
Printing out the which particular pattern caused the match is not particularly helpful. What you really want to do is use the result as a hash key, either to look up a "human-readable" result string or a callback function, whatever suits your needs. If your patterns have captures (e.g. /x=(\d+)/), they are available for use.
- another intruder with the mooring in the heart of the Perl
In reply to Re: Regex and question of design
by grinder
in thread Regex and question of design
by amaguk
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |