如何在 Perl 中用正斜杠替换反斜杠?
类似于这个,我该如何实现Perl 也一样吗?
我想转换:
C:\Dir1\SubDir1\` to `C:/Dir1/SubDir1/
我正在尝试遵循 此处 给出的示例,但是当我说类似的话:
my $replacedString= ~s/$dir/"/"; # $dir is C:\Dir1\SubDir1\
我收到编译错误。我尝试转义 /
,但随后出现其他编译器错误。
Similar to this, how do I achieve the same in Perl?
I want to convert:
C:\Dir1\SubDir1\` to `C:/Dir1/SubDir1/
I am trying to follow examples given here, but when I say something like:
my $replacedString= ~s/$dir/"/"; # $dir is C:\Dir1\SubDir1\
I get a compilation error. I've tried escaping the /
, but I then get other compiler errors.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
发布评论
评论(4)
~没有更多了~
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
= ~
与=~
有很大不同。第一个是赋值和按位求反,第二个是与正则表达式一起使用的绑定运算符。您想要的是这样的:
请注意使用全局
/g
选项来对整个字符串进行更改。在您的情况下,看起来您需要:如果您想要一个更具可读性的正则表达式,您可以交换分隔符:
s#\\#/#g;
如果您想保留原始字符串,您可以在进行替换之前复制它。您还可以使用音译:
tr#\\#/#
——在这种情况下,您不需要全局选项。简而言之:
文档:
= ~
is very different from=~
. The first is assignment and bitwise negation, the second is the binding operator used with regexes.What you want is this:
Note the use of the global
/g
option to make changes throughout your string. In your case, looks like you need:If you want a more readable regex, you can exchange the delimiter:
s#\\#/#g;
If you want to preserve your original string, you can copy it before doing the replacement. You can also use transliteration:
tr#\\#/#
-- in which case you need no global option.In short:
Documentation: