in reply to special characters in regexp

First, avoid using $a and $b; they're special.

If you are intending for $regexPattern to be a user supplied regex that may contain errors, then perhaps you want to *eval* the regex match and trap said errors.

my $matched; my $contender = 'foo'; my $regexPattern = '+foo'; #won't work eval { $matched = $contender =~ /$regexPattern/ }; warn $@ if $@; print "Hey, did I survive the error? Yay!\n";

Replies are listed 'Best First'.
Re^2: special characters in regexp
by JavaFan (Canon) on Jun 22, 2010 at 03:45 UTC
    First, $a and $b are probably just dummy variables to indicate the problem. And even if they do, most of the time, there's no problem at all when using $a and $b.

    But if we're nitpicking, if you shouldn't use a construct just because in some cases, this fails, you made a bigger boo-boo than the op with his $a and $b. You're trying to use $@ as an indication whether an eval failed or not. That's wrong; an eval may fail while $@ is false due to cleanup actions. The only way to be sure an eval succeeded is to check its return value:

    eval { $matched = $contender =~ /$regexPattern/; 1; } or warn $@ // "Unknown error";