|
Storing a regular expression in a perl variable
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 "$1\n";
}
This gave me the single result "SN" as being the only valid postcode within the areas listed in $local. (written 2006-02-09 05:08:13)
Associated topics are indexed under P669 - Perl - Data MungingP212 - Perl - More on Character Strings
Some other Articles
A fond memory of Sir FreddieIt costs nothing to say THANK YOUPerl/Tk real time displayShould we cruise around the world?Storing a regular expression in a perl variableThe magic of -textvariableAdd a friendly front end with TkTwice is a co-incidence and three times is a patternFinding where the disc space has goneNOT Gone phishing
|
1892 posts, page by page
Link to page ... 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38 at 50 posts per page
This is a page archived from The Horse's Mouth at
http://www.wellho.net/horse/ -
the diary and writings of Graham Ellis.
Every attempt was made to provide current information at the time the
page was written, but things do move forward in our business - new software
releases, price changes, new techniques. Please check back via
our main site for current courses,
prices, versions, etc - any mention of a price in "The Horse's Mouth"
cannot be taken as an offer to supply at that price.
Link to Ezine home page (for reading).
Link to Blogging home page (to add comments).
|
|