I'm trying to use a string as a regular expression inside another regular expression:
my $e = "a b";
if ('foo a b bar' =~ /foo ${e} bar/) {
print 'match!';
}
Doesn't work, since Perl treats as a special character. How do I escape it without changing the value of $e?
CodePudding user response:
You can use \Q and \E, which treats regexp metacharacters between them as literals:
#!/usr/bin/env perl
use strict;
use warnings;
use feature qw/say/;
my $e = "a b";
if ('foo a b bar' =~ /foo \Q$e\E bar/) {
say 'match!';
}
