#!/usr/bin/perl -w use strict; my $lhs = "abc"; my ($string1, $string2,$string3, $string4); $string1 = "qrsabcwty"; $string2 = "qrsabcwty"; $string3 = "qrsabcwty"; $string4 = "qrsabcwty"; my %lhsCompiled; #lets say the regex we want is $string1 =~ s/($lhs)/XXX$1/; # Then I compile it. my $rhsCompiled = qr{XXX$1}; $lhsCompiled{$lhs} = qr{($lhs)}; # This regex will not work $string2 =~ s/$lhsCompiled{$lhs}/$rhsCompiled/; # The left hand side works, but the right had side comes # out as (?-xism:XXXabc) # it returns qrs(?-xism:XXXabc)wty # instead I make the right hand side into a code block # using the e modifier which identifies the right hand side # as code block or a subroutine call. sub lhsSub {return "XXX".$1} $string3 =~ s/$lhsCompiled{$lhs}/lhsSub/e; $string4 =~ s/$lhsCompiled{$lhs}/"XXX".$1/e; # I suspect using a subroutine is faster. It will be compiled, # I am not certain if the code will be compiled print "string1 $string1\n"; print "string2 $string2\n"; print "string3 $string3\n"; print "string4 $string4\n"; #The results are # string1 qrsXXXabcwty # string2 qrs(?-xism:XXXabc)wty # string3 qrsXXXabcwty # string4 qrsXXXabcwty