perl – 在Moose中创建类属性的最佳方式是什么?

前端之家收集整理的这篇文章主要介绍了perl – 在Moose中创建类属性的最佳方式是什么?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我需要一个在Moose的类属性.现在我在说:
#!/usr/bin/perl

use 5.010;
use strict;
use warnings;
use MooseX::Declare;

class User {
    has id      => (isa => "Str",is => 'ro',builder => '_get_id');
    has name    => (isa => "Str",is => 'ro');
    has balance => (isa => "Num",is => 'rw',default => 0);

    #FIXME: this should use a database  
    method _get_id {
        state $id = 0; #I would like this to be a class attribute
        return $id++;
    }
}

my @users;
for my $name (qw/alice bob charlie/) {
    push @users,User->new(name => $name);
};

for my $user (@users) {
    print $user->name," has an id of ",$user->id,"\n";
}

解决方法

我发现MooseX :: ClassAttribute,但它看起来很丑陋.这是最干净的方式吗?
#!/usr/bin/perl

use 5.010;
use strict;
use warnings;
use MooseX::Declare;

class User {
    use MooseX::ClassAttribute;

    class_has id_pool => (isa => "Int",default => 0);

    has id      => (isa => "Str",default => 0);

    #FIXME: this should use a database  
    method _get_id {
        return __PACKAGE__->id_pool(__PACKAGE__->id_pool+1);
    }
}

my @users;
for my $name (qw/alice bob charlie/) {
    push @users,"\n";
}
原文链接:https://www.f2er.com/Perl/172450.html

猜你在找的Perl相关文章