Is a failed regex just a warning or is it an error?
A failed regexp is just that, it returns false. But compilation of the regexp - when it is put together - is an error that can be trapped, and the message can be viewed. So I recommend precompiling the regexp with the qr// operator (see perlop), so we can eval - and trap - just that part of the procedure.
Something like this will go through all your regexps and test them by compiling them before they are used:
my $regexp;
foreach( @regexps ) # Your regexps, from file.
{
eval "\$regexp = qr/$_/;" or die "Regexp error with regexp '$_': $
+@";
# ... use the regexp, it has passed QC:
&do_stuff() if( $testline =~ $regexp );
}
When a bad regexp is encountered, the loop will die with a message like this one:
Regexp error with regexp '\s//': Search pattern not terminated at (eva
+l 2) line 1
Which is something that can be read and understood, and hopefully also easily fixed. :) You could add a rowcount or something as well, to get the line in the file that the malformed regexp is at.
If you want to apply the good regexps, no matter if some fails, an approach like the one below should also work (within the loop):
if( eval "\$regexp = qr/$_/;" )
{
# Use regexp
}
else
{
warn "Regexp error with regexp '$_': $@";
}
Precompiling regexps with qr// can also, sometimes speed up the execution of the program if it is a heavily used one, and I think it can be well used to increase readability by matching /$url/ rather than /(https?|ftp):\/\/\w+\......../ and similar. Same thing if same regexp are used in several places, then you only need to change it in one place.
Hope this helps you. :)
You have moved into a dark place.
It is pitch black. You are likely to be eaten by a grue. |