It's a fine technique to use but you need to be a little careful about how you use it. Using double quotes to quote the pattern is a sure way to shoot yourself in the foot. It is better to use qr() for this.
Take your example, for example...
The first problem is that your hash initialization is all messed up and you have a typo too. We'll ignore that for the time being. The second problem with that is that you almost surely want character classes. I.e. "^0-9" will match a string that starts with the literal string "0-9". You mean probably mean either "[^0-9]" (anything that isn't a digit, better represented as \D) or "^[0-9]" (anything that starts with a digit, better represented by '^\d'. I'm going to assume its the latter you really wanted. See how I used single quotes around it? That's because if I used double quotes the \d would have looked like an escaped "d" which is simply a literal "d". So, the resulting regex would have matched anything that started with a "d" instead of a digit. That's why you shouldn't use double quotes.%character_tests{ "var1" , "^0-9", "var2" , "^A-Za-z0-9\." );
As I said, the qr() quoting operator is provided for just this sort of thing. You could write the snippet above as...
First, notice the assignment? That's required to initialize the hash. Notice also that I use parens. Braces are for hash refs. Don't worry about them right now. You really should pick more descriptive keys but those will suffice for now.%character_tests = ( var1 => qr/^0-9/, var2 => qr/^A-Za-z0-9\./ );
You would use such a regex like this:
You can also use them inside another regex.$somestring =~ $character_tests{var1};
Read perldoc perlop for more information on qr() and perldoc perlre for more information on regular expressions in general.$somestring =~ /$character_tests{var1}Foo/;
-sauoq "My two cents aren't worth a dime.";
In reply to Re: regex variables
by sauoq
in thread regex variables
by Angel
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |