views:

956

answers:

2

Is there any function like int() which can convert a string to float value? I'm currently using the following code:

$input=int(substr($line,1,index($line,",")-1));

I need to convert the string returned by substr to float.

+12  A: 

Just use it. In Perl, a string that looks like a number IS a number.

Now, if you want to be sure that the thing is a number before using it then there's a utility method in Scalar::Util that does it:

use Scalar::Util qw/looks_like_number/;

$input=substr($line,1,index($line,",")-1);

if (looks_like_number($input)) {
    $input += 1; # use it as a number!
}

Based on the sample input you left in the comments, a more robust method of extracting the number is:

$line =~ /([^\[\],]+)/; # <-- match anything not square brackets or commas
$input = $1;            # <-- extract match
slebetman
When I use the substr as is, I get the following error:Argument "1258200601.5027449," isn't numeric in int at test.pl
fixxxer
If that really is the error then your number has a comma in it which makes it not a number.
slebetman
Edit: removed int() because you wanted float... @fixxxer: sorry I copy/pasted from your example.
slebetman
+1  A: 

I don't know what your data looks like, but you do realize that the third argument to substr is a length, not a position, right? Also, the first position is 0. I suspect you aren't getting the data you think you are getting, and it mostly accidently works because you are starting at the beginning of the string and are only off by one.

brian d foy
The data starts with a "[".so it is wise that we start with 0 and not 1 as the second argument to substr.Ofcourse, the third one has to be a number.What in the code, makes you think that we overlooked that?
fixxxer
The index() makes me think you overlooked that, and the fact that you aren't extracting something that Perl thinks is a number. Show us a complete example with input data so we don't have to guess.
brian d foy