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:
When a bad regexp is encountered, the loop will die with a message like this one: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 ); }
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.Regexp error with regexp '\s//': Search pattern not terminated at (eva +l 2) line 1
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):
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.if( eval "\$regexp = qr/$_/;" ) { # Use regexp } else { warn "Regexp error with regexp '$_': $@"; }
Hope this helps you. :)
In reply to Re: eval and trapping bad regex
by Dog and Pony
in thread eval and trapping bad regex
by smackdab
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |