Erik Olson Erik Olson - 1 year ago 73
Perl Question

Predefining a complex replacement for substitution

I am trying to use variables in

. This example code works as expected:

my $regex1 = "e";
my $regex2 = "2";

my @array = ("one two three", "green blue red");

$_ =~ s/$regex1/$regex2/gee foreach (@array);

print $_ foreach (@array);

However, if I try to do a more complex regex, such as:

my $regex1 = "^(\w)";
my $regex2 = "\u$1";

Then the substitution doesn't work at all. I get the feeling Perl is literally looking for "caret parenthesis backslash" and so on, and not interpreting it as a regex.

Answer Source

You need to prevent interpolation of meta-characters:

my $regex1 = '^(\w)';
my $regex2 = '"\u$1"';

(Updated according to @ThisSuitIsBlackNot's comment)

The reason is that Perl interpolates double-quoted strings, so your variables $regex1 and $regex2 do not contain what you need:

my $regex1 = "^(\w)";
my $regex2 = "\u$1";
print "$regex1\n"; # ^(w)
print "$regex2\n"; # empty line

So, the substitution operator works as s/^(w)//gee and, of course, fails to find anything.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download