bmw0128
bmw0128

Reputation: 13698

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?

Upvotes: 4

Views: 1944

Answers (3)

Greg Hewgill
Greg Hewgill

Reputation: 992887

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.

Upvotes: 2

pilcrow
pilcrow

Reputation: 58534

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.

Upvotes: 5

fengshaun
fengshaun

Reputation: 2170

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

Upvotes: 1

Related Questions