简体   繁体   中英

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.

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/;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM