Perl String Substring

I want to replace something in a way like C:\foo , so I:

 s/hello/c:\foo 

But this is not true. Do I need to avoid some characters?

+4
source share
3 answers

Two problems that I see.

Your first problem is that your s/// replacement is not complete:

 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) 

The second problem you asked for is that \f is taken as a feed escape sequence (ASCII 0x0C), just like it would be in double quotes, which you don't want.

You can either avoid the backslash, or let the interpolation of variables β€œhide” the problem:

 s!hello!c:\\foo! # This will do what you want. Note double backslash. my $replacement = 'c:\foo' # NB: Using single quotes here, not double quotes s!hello!$replacement!; # This also works 

Take a look at the treatment of Quote and Quote perlop in perlop for more information.

+5
source

If I understand what you are asking, it could be something like what you need:

 $path = "hello/there"; $path =~ s/hello/c:\\foo/; print "$path\n"; 

To answer your question, yes, you need to double the backslash because \f is the escape sequence for "form feed" in the Perl line.

+2
source

The problem is that you are not avoiding special characters:

 s/hello/c:\\foo/; 

will solve your problem. \ is a special character, so you need to avoid it. {}[]()^$.|*+?\ are meta (special) characters that you need to avoid.

Additional link: http://perldoc.perl.org/perlretut.html

+1
source

Source: https://habr.com/ru/post/1313812/


All Articles