Catch regular expression errors with eval

D

David Liang

Sorry for the newcomer question; I couldn't find anything related.
What I'd like to do is compile and check if a regular expression is
proper:

$re = '[bad';
eval { $foo = qr/$re/; };
if ($@) {
# ...
}

I was thinking the eval would catch normally fatal errors, but it
doesn't catch the regex error. The program crashes with:

Unmatched [ in regex; marked by <-- HERE in m/[ <-- HERE bad/
at ...

Am I doing anything wrong? Is there a better way to do this?
Thanks.
 
U

Uri Guttman

DL> Sorry for the newcomer question; I couldn't find anything related.
DL> What I'd like to do is compile and check if a regular expression is
DL> proper:

DL> $re = '[bad';
DL> eval { $foo = qr/$re/; };
DL> if ($@) {
DL> # ...
DL> }

DL> I was thinking the eval would catch normally fatal errors, but it
DL> doesn't catch the regex error. The program crashes with:

DL> Unmatched [ in regex; marked by <-- HERE in m/[ <-- HERE bad/
DL> at ...

use eval string instead. eval block catches dies but that is a syntax
error and is fatal. eval string catches syntax errors and you can do the
same check. i don't recommend eval string often but this is one of those
cases where it is useful.

uri
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,007
Latest member
obedient dusk

Latest Threads

Top