views:

93

answers:

4

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?

+7  A: 

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).

ysth
+5  A: 

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.

DarkDust
+1  A: 

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.

KennyCason
A: 

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

rubber boots