I want to replace something with a path like C:\foo
, so I:
s/hello/c:\foo
But that is invalid. Do I need to escape some chars?
I want to replace something with a path like C:\foo
, so I:
s/hello/c:\foo
But that is invalid. Do I need to escape some chars?
If I understand what you're asking, then this might be something like what you're after:
$path = "hello/there";
$path =~ s/hello/c:\\foo/;
print "$path\n";
To answer your question, yes you do need to double the backslash because \f
is an escape sequence for "form feed" in a Perl string.
The problem is that you are not escaping special characters:
s/hello/c:\\foo/;
would solve your problem. \
is a special character so you need to escape it. {}[]()^$.|*+?\
are meta (special) characterss which you need to escape.
Additional reference: http://perldoc.perl.org/perlretut.html
Two problems that I can see.
Your first problem is that your s///
replacement is not terminated:
s/hello/c:\foo # fatal syntax error: "Substitution replacement not terminated"
s/hello/c:\foo/ # syntactically okay
s!hello!c:\foo! # also okay, and more readable with backslashes (IMHO)
Your second problem, the one you asked about, is that the \f
is taken as a form feed escape sequence (ASCII 0x0C), just as it would be in double quotes, which is not what you want.
You may either escape the backslash, or let variable interpolation "hide" the problem:
s!hello!c:\\foo! # This will do what you want. Note double backslash.
my $replacement = 'c:\foo' # N.B.: Using single quotes here, not double quotes
s!hello!$replacement!; # This also works
Take a look at the treatment of Quote and Quote-like Operators in perlop
for more information.