I have the following string ./test
and I want to replace it with test
so, I wrote the following in perl: my $t =~ s/^.//;
however, that replaces ./test
with /test
can anyone please suggest how I fix it so I get rid of the /
too. thanks!
my $t =~ s/^\.\///;
You need to escape the dot and the slash.
The substitution is s/match/replace/
. If you erase, it's s/match//
. You want to match "starts with a dot and a slash", and that's ^\\.\\/
.
The dot doesn't do what you expect - rather than matching a dot character, it matches any character because of its special treatment. To match a dot and a forward slash, you can rewrite your expression as follows:
my $t =~ s|^\./||;
Note that you are free to use a different character as a delimiter, in order not to confuse it with any such characters inside the regular expression.
If you want to get rid of ./
then you need to include both of those characters in the regex.
s/^\.\///;
Both .
and /
have special meanings in this expression ( .
is a regex metacharacter meaning "any character" and /
is the delimiter for the s///
operator) so we need to escape them both by putting a \\
in front of them.
An alternative (and, in my opinion, better) approach to the /
issue is to change the character that you are using as the s///
delimiter.
s|^\./||;
This is all documented in perldoc perlop .
You have to use a backward slash before the dot and the forward slash: s/\\.\\//; The backslash is used to write symbols that otherwise would have a different meaning in the regular expression.
You need to write my $t =~ s/^\\.\\///;
(Note that the period needs to be escaped in order to match a literal period rather than any character). If that's too many slashes, you can also change the delimiter, writing instead, eg, my $t =~ s:^\\./::;
.
$t=q(./test);$t=~s{^\./}{};print $t;
You need to escape the dot if you want it to match a dot. Otherwise it matches any character. You can choose alternate delimiters --- best when dealing with forward slashes lest you get the leaning-toothpick look when you otherwise need to escape those too.
Note that the dot in your question is matching any character, not a literal '.'.
my $t = './test';
$t =~ s{\./}{};
use Path::Class qw( file );
say file("./test")->cleanup();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.