Catch regular expression errors with eval

Discussion in 'Perl Misc' started by David Liang, Sep 21, 2009.

  1. David Liang

    David Liang Guest

    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.
    David Liang, Sep 21, 2009
    #1
    1. Advertising

  2. David Liang

    Uri Guttman Guest

    >>>>> "DL" == David Liang <> writes:

    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
    Uri Guttman, Sep 21, 2009
    #2
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. VSK
    Replies:
    2
    Views:
    2,289
  2. Mark Goldin

    Errors, errors, errors

    Mark Goldin, Jan 17, 2004, in forum: ASP .Net
    Replies:
    2
    Views:
    942
    Mark Goldin
    Jan 17, 2004
  3. John Black
    Replies:
    8
    Views:
    4,152
    Xenos
    Aug 20, 2004
  4. Barun Singh
    Replies:
    4
    Views:
    137
    Robert Klemme
    Jan 29, 2009
  5. graphicsxp

    issue with eval and regular expression

    graphicsxp, Jun 11, 2009, in forum: Javascript
    Replies:
    7
    Views:
    155
    Evertjan.
    Jun 13, 2009
Loading...

Share This Page