Archive for November, 2003

Nov
18

Checking Regular Expression Syntax

Posted by: celso | Comments (0)

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.
}
Categories : Notes, Perl
Comments (0)

Gallery