在perl中解析字符串中的负数
如何在 perl 中解析字符串中的负数?我有这段代码:
print 3 - int("-2");
它给了我 5
,但我需要 3
。我该怎么做?
How do I parse a negative number from a string in perl? I have this piece of code:
print 3 - int("-2");
It gives me 5
, but I need to have 3
. How do I do it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
Perl 会根据需要自动在字符串和数字之间进行转换;不需要 int() 操作,除非您确实想要将浮点数(无论存储为数字还是字符串)转换为整数。所以你可以这样做:
并得到 5(因为 3 减去负 2是 5)。
Perl will automatically convert between strings and numbers as needed; no need for an int() operation unless you actually want to convert a floating point number (whether stored as a number or in a string) to an integer. So you can just do:
and get 5 (because 3 minus negative 2 is 5).
好吧,3 - (-2) 实际上是 5。我不太确定你想要实现什么,但是如果你想过滤掉负值,为什么不做这样的事情:
这会将你的负值变成 0 但是让正数通过。
Well, 3 - (-2) really is 5. I'm not really sure what you want to achieve, but if you want to filter out negative values, why not do something like this:
This will turn your negative values to 0 but lets the positive numbers pass.
看来解析正确。
3 - (-2) 是 5。
如果它错误地将 -2 解析为 2,那么它将输出 3 - 2 = 1。
无论你如何从 3 中加/减 2,你都永远不会得到 3。
It seems to be parsing it correctly.
3 - (-2) is 5.
If it was mistakenly parsing -2 as 2 then it would have output 3 - 2 = 1.
No matter how you add/subtract 2 from 3, you will never get 3.
您可能正在考虑其他一些函数而不是“int”。
尝试:
如果你想得到 3 结果。
问候
rbo
You are probably thinking of some other function instead of 'int'.
try:
if you want to get 3 as result.
Regards
rbo