如何在 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;});
main.pl
use strict;
use warnings;
use PROBLEM;
my $problem=PROBLEM->new();
How can I declare a class variable as floating point in Moose?
My (fictional) sample below produces errors for "Real", "Number" etc ... "Str" works but defeats the purpose .. searching/Google doesn't help, since I can't hit the correct search terms...
PROBLEM.pm
package PROBLEM;
use strict;
use warnings;
use Moose;
has 'PROBLEM'=> (isa=>'real',is =>'ro',required=>'0',default=>sub {0.1;});
main.pl
use strict;
use warnings;
use PROBLEM;
my $problem=PROBLEM->new();
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
查看 Moose 类型 文档。没有内置的浮点类型,只有
Num
及其子类型Int
。这是有道理的,因为 Perl 实际上并没有(明显)区分浮点数和整数。最好的办法可能是使用
Num
作为类型约束,或者编写您自己的类型,将值强制转换为适合您需要的某种形式。Check out the Moose Types documentation. There is no built-in float type, just
Num
and its subtypeInt
. This makes sense, since Perl really doesn't differentiate (visibly) between floats and integers.The best thing to do is probably to use
Num
as the type constraint, or write your own type that coerces the value into some form that suits your needs.您需要 Num 类型来获取实数:
You need Num type for a real number: