Erik Olson Erik Olson - 1 year ago 68
Perl Question

Perl substitutions: evaluating parentheses and back references not working

I am trying to use variables in s///. 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 sub does not 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. I'm not sure how to fix this.


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