I have a find_replace subroutine that takes in parameters (content, find regex, replace regex, result variable to store result in). I use qr//
to pass both the find and replace regex. Find regex works well, but the replace regex doesn't.
$text = "11 22 33 44 55";
find_replace($text,qr/(33 )(.*?)( 55)/,qr/$1<BOLD>$2<\/BOLD>$3/,my $newText);
print $newText;
#Should print: 11 22 <I>33 <B>44</B> 55</I>
#But it prints: 11 22 <I>(?^:<B></B>)</I>
sub find_replace {
my $content = shift;
my $findRegEx = shift;
my $replaceRegEx = shift;
my $newVariable = \shift;
${$newVariable} = $content;
${$newVariable} =~ s/$findRegEx/<I>$replaceRegEx<\/I>/g;
}
I've found a fix for this to work:
$text = "11 22 33 44 55";
find_replace($text,qr/(33 )(.*?)( 55)/,sub{"$1<B>$2<\/B>$3"},my $newText);
print $newText;
#Prints: 11 22 <I>33 <B>44</B> 55</I>
sub find_replace {
my $content = shift;
my $findRegEx = shift;
my $replaceRegEx = shift;
my $newVariable = \shift;
${$newVariable} = $content;
${$newVariable} =~ s($findRegEx){ "<I>".$replaceRegEx->()."<\/I>" }ge;
}
But this fix uses sub{"…"}
instead of qr/…/
. What I'm looking for is to keep using the qr//
for passing the replace regex and get the same result.