string 如何在 Perl 中用正斜杠替换反斜杠?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8014556/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to replace backslash with forward slash in Perl?
提问by user375868
Similar to this, how do I achieve the same in Perl?
与此类似,我如何在 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 forward slash, but I then get other compiler errors.
我收到编译错误。我试过转义正斜杠,但随后出现其他编译器错误。
回答by TLP
= ~
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:
你想要的是这个:
$string_to_change =~ s/pattern_to_look_for/string_to_replace_with/g;
Note the use of the global /g
option to make changes throughout your string. In your case, looks like you need:
请注意使用全局/g
选项在整个字符串中进行更改。在你的情况下,看起来你需要:
$dir =~ s/\/\//g;
If you want a more readable regex, you can exchange the delimiter: s#\\#/#g;
如果你想要一个更易读的正则表达式,你可以交换分隔符: 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.
如果要保留原始字符串,可以在替换之前复制它。您还可以使用音译:tr#\\#/#
-- 在这种情况下,您不需要全局选项。
In short:
简而言之:
$dir =~ tr#\#/#;
Documentation:
文档:
回答by Mike Samuel
You're splitting the =~
operator and missing the global modifier. Just assign $dir
to $replacedString
and then do the substitution.
您正在拆分=~
运算符并缺少全局修饰符。只需分配$dir
给$replacedString
然后进行替换。
my $replacedString = $dir;
$replacedString =~ s|\|/|g;
You can use tr
, the translate operator, instead of the s
operator too to get simpler code.
您也可以使用tr
翻译运算符代替s
运算符来获得更简单的代码。
my $replacedString = $dir;
$replacedString =~ tr|\|/|;
回答by Sinan ünür
You might actually be looking for File::Spec->canonpathor Path::Classwithout realizing it.
您可能实际上正在寻找File::Spec->canonpath或Path::Class而没有意识到。
回答by Akshit
use warnings;
use strict;
my $str = 'c:/windows/';
$str =~ tr{/}{\};
print $str;
Output:
输出:
c:\windows\
c:\windows\