Question

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.

Was it helpful?

Solution

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

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top