Kevin Dunn
Kevin Dunn

Reputation: 13

Replacing text with backslashes with perl substitution command

So I was working on a perl script that does substitution commands on input and the input will have backslashes. So just replace some text with new text

For example, if the input was

"\text"

I might output

"newText"

Note that the slash is removed.

Here is some code that does that:

$oldText = "\\Text";

while (<STDIN>) {                
    $ln = $_;                     
    $ln2 = $_;
    $ln2 =~ s/\\Text/newText/;  
    $ln =~ s/$oldText/newText/;
}
print "$ln\n";
print "$ln2\n";

When the input is "Text" the output is

\newText #Incorrect because the \ is still there

newText #Correct

Can anyone explain why using the string instead of a variable changes the output to be what I want? I'm aware that \ derefences the following character, and that is likely the source of the issue. But I can't fathom why having using a variable changes the output. Changing the variable oldText to be "\text" doesn't change the output.

Upvotes: 0

Views: 469

Answers (1)

choroba
choroba

Reputation: 241818

Using warnings would have told you:

Unrecognized escape \T passed through in regex; marked by <-- HERE in m/\T <-- HERE ext/ at ...

$oldText = "\\Text" assigns the string \Text to $oldText, so the two substitutions aren't equivalent. Use \Q (see quotemeta) to quote the contents of a variable:

$ln =~ s/\Q$oldText/newText/;

Upvotes: 4

Related Questions