I have a very specific problem.

Does s/// work with strings that are contained in single quotes? I've been debugging and I'm trying to replace a string that contains a $ in it. If I use double quotes, it works for the string up until the $. If I use single quotes, it does not work with any string.

Here is my code; it involves file access, and file.data contains the string "testing $my string."

#!/usr/bin/perl

$s1 = "testing $my string";
$s2 = "testing $your string";

local ($^I, @ARGV) = ('.bak', 'file.data');
while (<>) {
        s/$s1/$s2/g;
  print;
}

Recommended Answers

All 3 Replies

#!/usr/bin/perl

$s1 = "testing $my string";
$s2 = "testing \$your string";

local ($^I, @ARGV) = ('.bak', 'file.data');
while (<>) {
        s/\Q$s1\E/$s2/g;
  print;
}

I added an escape \ to $s1 like you did to $s2 and it worked great, thanks!

Ahh, now that I think about it \Q does not affect $ in a regexp, so you would use the quotemeta() function or add the escape character manually like you did.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.