开发者

How can I convert a string to a float with Perl?

开发者 https://www.devze.com 2022-12-15 21:15 出处:网络
Is there any function like int() which can convert a string to float value? I\'m currently using the following code:

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 con开发者_Go百科vert the string returned by substr to float.


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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消