Writing to read-only attributes inside a Perl Moose class

后端 未结 3 903
别那么骄傲
别那么骄傲 2021-01-12 19:06

Using Perl and Moose, object data can be accessed in 2 ways.

$self->{attribute} or $self->attribute()

Here is a si

3条回答
  •  粉色の甜心
    2021-01-12 19:35

    I don't think $self->{age} is a documented interface, so it's not even guaranteed to work.

    In this case I'd use a private writer as described in https://metacpan.org/pod/Moose::Manual::Attributes#Accessor-methods:

    has 'weight' => (
        is     => 'ro',
        writer => '_set_weight',
    );
    

    You could even automate this using 'rwp' from https://metacpan.org/pod/MooseX::AttributeShortcuts#is-rwp:

    use MooseX::AttributeShortcuts;
    
    has 'weight' => (
        is => 'rwp',
    );
    

提交回复
热议问题