如何在 Moose 中将类变量声明为浮点型?

发布于 2024-08-05 10:21:46 字数 461 浏览 8 评论 0原文

如何在 Moose 中将类变量声明为浮点型?

下面我的(虚构的)示例会产生“真实”、“数字”等错误...“Str”有效,但达不到目的。搜索/谷歌没有帮助,因为我无法找到正确的搜索词。


PROBLEM.pm

package PROBLEM;
use strict;
use warnings;
use Moose;

has 'PROBLEM'=> (isa=>'real',is =>'ro',required=>'0',default=>sub {0.1;});

ma​​in.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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

淡淡绿茶香 2024-08-12 10:21:46

查看 Moose 类型 文档。没有内置的浮点类型,只有 Num 及其子类型 Int。这是有道理的,因为 Perl 实际上并没有(明显)区分浮点数和整数。

最好的办法可能是使用 Num 作为类型约束,或者编写您自己的类型,将值强制转换为适合您需要的某种形式。

Check out the Moose Types documentation. There is no built-in float type, just Num and its subtype Int. 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.

苄①跕圉湢 2024-08-12 10:21:46

您需要 Num 类型来获取实数:

{
    package Problem;
    use Moose;

    has 'number' => ( 
        isa      => 'Num', 
        is       => 'ro', 
        default  => sub { 0.1 },
    );
}


my $problem = Problem->new;
say $problem->number;  # => 0.1

You need Num type for a real number:

{
    package Problem;
    use Moose;

    has 'number' => ( 
        isa      => 'Num', 
        is       => 'ro', 
        default  => sub { 0.1 },
    );
}


my $problem = Problem->new;
say $problem->number;  # => 0.1
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文