(e-mail address removed) wrote:
I have
s/$foo/$bar/;
But $foo and $bar might have funny characters [ ] { } etc., and I want
them taken literally rather than parsed as regular expressions.
How can I do this substitution? Thanks.
s/\Q$foo\E/$bar/;
Unfortunately, \Q will not do some regex esc characters. If $foo is dynamic
and unknown, then that is a problem. I have a simple sub that does it all.
I don't know why Perl doesn't do all of them, have to ask the designers.
This is meant to the OP (not "it_says_BALLS_on_your forehead"):
To followup (I should have included everything).
The basic problem on the left (regex) side is that either its dynamic
or static. If its static, you can intermix escaped escape codes with escape
codes. If its dynamic, that is not possible.
The *only* reason to have dynamic regex is to compare a source with a target
within a loop. Ie: the regex is the last source (for example). In this case
\Q won't cut it (see the docs).
Try this to convert patterns (pattern side of regex, not replacement. ie: m/$pattern/$replacement/):
sub convertPatternMeta
{
my ($pattern) = shift;
my @regx_esc_codes =
(
"\\", '/', '(', ')', '[', ']', '?', '|',
'+', '.', '*', '$', '^', '{', '}', '@'
);
foreach my $tc (@regx_esc_codes) {
# code template for regex
my $xxx = "\$pattern =~ s/\\$tc/\\\\\\$tc/g;";
eval $xxx;
if ($@) {
# the compiler will show the escape char, add
# it char to @regx_esc_codes
$@ =~ s/^[\s]+//s; $@ =~ s/[\s]+$//s;