我怎样才能将字符串转换为Perl的浮动? [英] How can I convert a string to a float with Perl?

查看:147
本文介绍了我怎样才能将字符串转换为Perl的浮动?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有像 int()这样的可以将字符串转换为浮点值的函数?
我目前正在使用下面的代码:

$ $ p $ $ $ $ $ $ $ $ input $ int $ substr($ line,1,index ($线, ) - 1));

我需要转换由 substr to float。

解决方案

请使用它。在Perl中,一个看起来像一个数字的字符串是一个数字。



现在,如果你想确定这个东西是之前的数字>使用它,然后在 Scalar :: Util 中有一个实用方法:

  use Scalar :: Util qw / looks_like_number /; 

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

if(looks_like_number($ input)){
$ input + = 1; #用它作为数字!
}

基于您在留言中留下的样本输入,提取的数字是:

$ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $'$' #< - 匹配任何不是方括号或逗号
$ input = $ 1; #< - 提取匹配


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.

解决方案

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

这篇关于我怎样才能将字符串转换为Perl的浮动?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆