lex*_*exu 7 floating-point perl moose
如何在Moose中将类变量声明为浮点?
我下面的(虚构的)样本产生的"真实","数字"等等......"STR"的作品错误,但失败的目的..搜索/谷歌没有帮助,因为我打不正确的搜索词.. .
PROBLEM.pm
package PROBLEM;
use strict;
use warnings;
use Moose;
has 'PROBLEM'=> (isa=>'real',is =>'ro',required=>'0',default=>sub {0.1;});
Run Code Online (Sandbox Code Playgroud)
main.pl
use strict;
use warnings;
use PROBLEM;
my $problem=PROBLEM->new();
Run Code Online (Sandbox Code Playgroud)
查看Moose Types文档.没有内置浮点类型,只是Num
它的子类型Int
.这是有道理的,因为Perl实际上并没有区分(可见)浮点数和整数.
最好的办法可能是Num
用作类型约束,或编写自己的类型,将值强制转换为适合您需要的形式.
你需要Num类型的实数:
{
package Problem;
use Moose;
has 'number' => (
isa => 'Num',
is => 'ro',
default => sub { 0.1 },
);
}
my $problem = Problem->new;
say $problem->number; # => 0.1
Run Code Online (Sandbox Code Playgroud)