Ano-Tech Computers
Enter keyword:

Perl: How to include variables in a regular expression
Problem:
Now and then you want to include a variable string in a regular expression like this: "if (/\w{1,4}$var_(\d*)/)" Unfortunately, this will confuse the compiler, because it can't decide exactly what the variable name is, and incorrectly try to use "$var_". But the variable you wanted to use was "$var".
 
Solution:
By using the escape codes \Q and \E you can tell the compiler where the variable name begins and ends.

Example:
"if (/\w{1,4}\Q$var\E_(\d*)/) "

Thanks to Savuud for this one!! :-)

 
Discuss this solution
Did this article solve your problem? Yes No Did not apply

We welcome anyone who is willing to contribute to this public knowledge base, contact siteadmin@atc.no if you have information you would like to share. The idea is not to replace the commercial support sites, but to publish those hard-to-find solutions you've found yourself looking for over and over again.

Show all articles