如何从非数字字符串的替换中获得数字?
我是 perl 新手,有一个小问题:
perl 代码的一部分:
print "${data_dir}\n";
#converting directory path to unix format (replacing all backslashes with slashes)
$data_dir = ~s/\\/\//g;
print "${data_dir}\n";
输出:
C:/dev/../data
4294967295
为什么结果不同?我猜想问题出在 $data_dir
变量中,因为这适用于其他字符串,但问题可能是什么?
PS $data_dir
我是从其他模块获取的,不知道它是如何构造的。
I'm new in perl and have a little problem:
part of perl code:
print "${data_dir}\n";
#converting directory path to unix format (replacing all backslashes with slashes)
$data_dir = ~s/\\/\//g;
print "${data_dir}\n";
output:
C:/dev/../data
4294967295
Why results are different? I guess that the problem in $data_dir
variable, because this works for other string, but what can be the problem?
P.S. $data_dir
I'm getting from other module, and don't know how it is constructed.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
= 和 ~ 之间有一个空格。他们应该在一起=~。
您所做的是将 $data_dir 设置为等于
s/\\/\//g
的补码(即 ~ 运算符),等于 4294967295。You have a space between the = and the ~. They should be together =~.
What you were doing is setting $data_dir equal to the complement (i.e. the ~ operator) of
s/\\/\//g
which equals 4294967295.真的是“=~”里面有空格吗?
应该是“=~”,没有空格。您当前正在为 $data_dir 分配字符串的按位求反值。
您正在使用以下内容,不是吗?
使用严格;
使用警告;
Is that really "= ~" with a space in it?
It should be "=~" with no space. You are currently assigning $data_dir the bitwise negated value of the string.
Your are using the following aren't you?
use strict;
use warnings;
其他人已经回答了问题的原因 -
= ~
之间的空格,应该是=~
没有空格。一个宝贵的教训是始终将
use strict
添加到您的脚本中;如果您这样做,您会收到如下警告:这将帮助您找出替换运算符正在
$_
而不是$data_dir - 因为您没有使用绑定运算符
=~
将其绑定到$data_dir
,而是使用了= ~
。因此,要吸取的教训是:始终
使用严格
- 这将有助于捕获此类情况(您可能会出现单个字符错误),并节省大量时间。顺便说一句,当使用文件路径并希望在平台之间实现可移植性时,使用 File::Spec 是通常是个好主意。
Others have already answered with the cause of the problem - the space between
= ~
, which should have been=~
without the space.A valuable lesson is to always add
use strict
to your scripts; if you'd done so, you would have received a warning like:That would have helped you to figure out that the substitution operator was being used on
$_
rather than on$data_dir
- because instead of the binding operator=~
binding it to$data_dir
, you had= ~
.So, lesson to learn: always
use strict
- it'll help catch things like this, where you could have a single character wrong, and save you a lot of time.Incidentally, when working with file paths and desiring portability between platforms, using File::Spec is often a good idea.
这是因为您对 s/..../g 应用了数字运算符 (~)。
请尝试以下操作:
It is because you apply a numeric operator (~) to s/..../g.
Try the following: