gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 01:04:53 24 4
gpt4 key购买 nike

我需要 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", is => 'rw', default => 0);

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 {
return __PACKAGE__->id_pool(__PACKAGE__->id_pool+1);
}
}

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";
}

关于perl - 在 Moose 中创建类属性的最佳方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1056228/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com