简体   繁体   English

如何在 Perl hash 中将字符串转换为浮点数?

[英]How to convert string to floating point number inside a Perl hash?

My motive is to convert the string number into floating point number while creating a hash.我的动机是在创建 hash 时将字符串数转换为浮点数。

I have placed my entire code and error below.我把我的整个代码和错误放在下面。 Please help me to solve this issue.请帮我解决这个问题。

Sample code示例代码

use strict;
use warnings;

use Data::Dumper;

my $price = 8.5;

my $g={};
$g->{'get'}=sprintf('%.02f',$price);

print Dumper($g);

Current output当前 output

$VAR1 = {
          'get' => '8.50'
        };

Expected output预期 output

$VAR1 = {
          'get' => 8.50
        };

Despite the single quotes around 8.50 in the Dumper output, Perl will still treat it as a numeric value when you go to use it:尽管Dumper output 中的单引号约为8.50 ,但当您使用 go 时,Perl 仍会将其视为数值:

use strict;
use warnings;

my $price = 8.5;

my $g={};
$g->{'get'}=sprintf('%.02f',$price);

my $x = 5;
printf "%.02f\n", $x + $g->{get};

Outputs:输出:

13.50
use Scalar::Util 'looks_like_number';
.
.
print Dumper($g) =~ s/'(.*?)'/looks_like_number($1)?$1:"'$1'"/ger;

Which changes the output from Dumper before it's printed.这会在打印之前从 Dumper 更改 output。 It removes both ' s of every single quoted string if it looks like a number according to Scalar::Util.如果根据 Scalar::Util,它看起来像一个数字,它会删除每个单引号字符串的两个'

I suspect you're worrying unnecessarily here.我怀疑你在这里不必要地担心。 Perl treats strings and numbers as largely interchangeable and will generally do the right thing with data of either type. Perl 将字符串和数字视为在很大程度上可以互换,并且通常会对任何一种类型的数据做正确的事情。 The number of times when you should care if you have a string or a number is tiny.如果你有一个字符串或一个数字,你应该关心的次数很少。

In fact, even if you explicitly give Perl a number in code like yours, it will be displayed as a string:事实上,即使你在像你这样的代码中明确地给 Perl 一个数字,它也会显示为一个字符串:

$ perl -MData::Dumper -E'say Dumper { get => 8.5 }'
$VAR1 = {
          'get' => '8.5'
        };

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM