tags:

views:

87

answers:

3
+3  Q: 

Perl string sub

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?

+2  A: 

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.

Greg Hewgill
The last sentence is wrong, in fact `\f` is a valid escape sequence for *form feed*.
daxim
True, fixed. Form feed is not one I would use often!
Greg Hewgill
+1  A: 

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

fengshaun
+4  A: 

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.

pilcrow