Checking Regular Expression Syntax

If your program accepts a regular expression pattern, either from a user input or another module, you need to check that the pattern you receive is valid or not. To check for a valid pattern, apply the pattern against an empty string and wrap the expression in an eval.


sub my_func {
    my ($pattern) = @_;

    eval {
        "" =~ $pattern;
    };
    if ($@) {
        die "Something wrong with your pattern: $pattern";
    }

    # Otherwise, pattern is good and use it here.
}

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.