Main Content

Storing a regular expression in a perl variable

Archive - Originally posted on "The Horse's Mouth" - 2006-02-09 05:08:13 - Graham Ellis

When you match to a regular expression in a perl program, the program has to compile the regular expression (i.e. work out what it does) before actually doing the matching. It's pretty smart about that - it stored the result of than compile so that it only has to do it once during each run. However, if the regular expression contains a variable, Perl is slowed right down as the variable could change and Perl has to recompile every time.

If the variable isn't, in fact, going to change very often during a run you can control the compiling yourself by using a scalar variable to store the compiled regular expression using qr, as shown in this example:

  
$local = "TR|PL|EX|TQ|TA|SN|BA|BS|DT|BH|GL";
$pcode = qr/^\s*($local)\d\w?\s+\d[A-Z]{2}\s*$/;

@vcheck = ("SN12 6QL","G3 7XR","GLZ 7PX"," OX11 0EY","NW1 1AD");

foreach $tp (@vcheck) {
$tp =~ $pcode and print "\n";
}


This gave me the single result "SN" as being the only valid postcode within the areas listed in $local.