在perl中解析字符串中的负数

发布于 2024-09-14 09:10:37 字数 136 浏览 2 评论 0原文

如何在 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

黄昏下泛黄的笔记 2024-09-21 09:10:37

Perl 会根据需要自动在字符串和数字之间进行转换;不需要 int() 操作,除非您确实想要将浮点数(无论存储为数字还是字符串)转换为整数。所以你可以这样做:

my $string = "-2";
print 3 - $string;

并得到 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:

my $string = "-2";
print 3 - $string;

and get 5 (because 3 minus negative 2 is 5).

像你 2024-09-21 09:10:37

好吧,3 - (-2) 实际上是 5。我不太确定你想要实现什么,但是如果你想过滤掉负值,为什么不做这样的事情:

$i = int("-2")
$i = ($i < 0 ? 0 : $i);

这会将你的负值变成 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:

$i = int("-2")
$i = ($i < 0 ? 0 : $i);

This will turn your negative values to 0 but lets the positive numbers pass.

阪姬 2024-09-21 09:10:37

看来解析正确。
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.

魄砕の薆 2024-09-21 09:10:37

您可能正在考虑其他一些函数而不是“int”。

尝试:

 use List::Util qw 'max';

 ...

 print 3 - max("-2", 0);

如果你想得到 3 结果。

问候

rbo

You are probably thinking of some other function instead of 'int'.

try:

 use List::Util qw 'max';

 ...

 print 3 - max("-2", 0);

if you want to get 3 as result.

Regards

rbo

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文