Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perl string sub

Tags:

perl

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?

like image 460
bmw0128 Avatar asked Feb 27 '23 19:02

bmw0128


2 Answers

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.

like image 119
pilcrow Avatar answered Mar 06 '23 23:03

pilcrow


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.

like image 39
Greg Hewgill Avatar answered Mar 06 '23 23:03

Greg Hewgill