I have a Perl program that stores regular expressions in configuration files. They are in the form:
regex = ^/d+$
Elsewhere, the regex gets parsed from the file and stored in a variable – $regex. I then use the variable when checking the regex, e.g.
$lValid = ($valuetocheck =~ /$regex/);
I want to be able to include perl variables in the config file, e.g.
regex = ^\d+$stored_regex$
But I can’t work out how to do it.
When regular expressions are parsed by Perl they get interpreted twice. First the variables are expanded, and then the the regular expression itself is parsed.
What I need is a three stage process: First interpolate $regex, then interpolate the variables it contains and then parse the resulting regular expression. Both the first two interpolations need to be ‘regular expression aware’. e.g. they should know that the string contain $ as an anchor etc…
Any ideas?
Using eval can help you here. Take a look at the following code it can precompile a regexp that’s ready to be used latter:
The operator qr// can be used to precompile a regexp. It lets you build it but doesn’t execute it yet. You can first build your regexps with it and then use them latter.