How to convert string to float with Perl?

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

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

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

+2
source share
2 answers

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 the number before using it, then there is a utility method in Scalar::Util that does this:

 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 input of the sample that you left in the comments, a more reliable way to extract the number:

 $line =~ /([^\[\],]+)/; # <-- match anything not square brackets or commas $input = $1; # <-- extract match 
+17
source

I don’t know what your data looks like, but you understand that the third argument of substr is the length, not the position, right? In addition, the first position is 0. I suspect that you are not receiving the data that you think you are receiving, and this basically randomly works because you start at the beginning of the line and are only disabled.

+1
source

Source: https://habr.com/ru/post/915669/


All Articles