I often want to do something like $a =~ s/$b/$c/g , where $b is a variable that may have regex metacharacters in it. Here's an example of the problem:
my $a = "$";
my $b = "$";
my $c = "x";
$a =~ s/$b/$c/g;
print "a=$a\n";
This results in an error, because the string $b has a regex metacharacter, $, in it.
Here's the alternative I've come up with so far:
# conceptually, the following is like $a=~s/$b/$c/, but is safe if $b
+has metacharacters in it
sub string_substitution_one {
my $a_ref = shift;
my $b = shift;
my $c = shift;
my $a = $$a_ref;
my $debug = ($b eq '$m$');
my $i=index($a,$b);
return 0 if $i == -1;
my $z = '';
if ($i>0) {$z = $z . substr($a,0,$i)}
$z = $z . $c;
if ($i+length($b)<length($a)) {$z = $z . substr($a,$i+length($b),len
+gth($a)-($i+length($b)))}
$$a_ref = $z;
return 1;
}
# conceptually, the following is like $a=~s/$b/$c/g, but is safe if $b
+ has metacharacters in it
sub string_substitution_global {
my $a_ref = shift;
my $b = shift;
my $c = shift;
my $found = 0;
while (string_substitution_one($a_ref,$b,$c)) {
$found = 1;
}
return $found;
}
Is there a simpler way to do this? I'm thinking of making this into a module, because I have several different programs that use it, but it seems like there must be an easier way to do such a common task.
TIA!