Skrevet av Emne: Perl: How to include variables in a regular expression  (Lest 2366 ganger)

ATC

  • Gjest
Perl: How to include variables in a regular expression
« på: 27. ſeptember 2008, 18:24 pm »
  • [applaud]0
  • [smite]0
  • 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".



    ATC

    • Gjest
    [Solved] Perl: How to include variables in a regular expression
    « Svar #1 på: 27. ſeptember 2008, 18:24 pm »
  • [applaud]0
  • [smite]0
  • 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!! :-)