0

I have a short question: Is it possible to store a Regex as string in a variable (ok, I know that is possible) and then execute it?

Or is the only possibility to store and use the match and substitution pattern in a variable?

Thanks in advance for your help!

Mäx Müller
  • 233
  • 1
  • 3
  • 15

1 Answers1

9

You can use qr// quotes to keep a precompiled regex object in a scalar variable:

my $re = qr/foo/;

"foobar" =~ $re;        # works
"foobar" =~ /$re/;      # the same thing
"foobar" =~ /${re}bar/; # compose your regexes
"foobar" =~ s/$re/baz/; # use in substitutions
"$re"; # a version-dependent stringification of the regex
       # that is equivalent to your pattern.
amon
  • 57,091
  • 2
  • 89
  • 149