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

Igo*_*yev 0 perl parsing integer negative-number

如何从perl中解析字符串中的负数?我有这段代码:

print 3 - int("-2");
Run Code Online (Sandbox Code Playgroud)

它给了我5,但我需要3.我该怎么做?

yst*_*sth 8

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

my $string = "-2";
print 3 - $string;
Run Code Online (Sandbox Code Playgroud)

得到5(因为3减负2 5).


Dar*_*ust 5

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

$i = int("-2")
$i = ($i < 0 ? 0 : $i);
Run Code Online (Sandbox Code Playgroud)

这会将您的负值变为0,但允许正数通过.