Search code examples
perlmoose

accessing a Moose Array


Having trouble figuring out the syntax (which I'm sure is obvious and I'm stupid) for pushing to a Moose array. This is a continuation of this question. it seems to me that I need to more than a simple value for my specific case. Trying to implement it using a Moose-ish way (maybe that's wrong?) but I'm obviously not doing it right.

use Moose::Role;
has 'tid_stack' => (
    traits => ['Array'],
    is     => 'rw',
    isa    => 'ArrayRef[Str]',
    default => sub { [] },
);


around 'process' => sub {
    my $orig = shift;
    my $self = shift;
    my ( $template ) = @_;

    $self->tid_stack->push( get_hrtid( $template ) );

    $self->$orig(@_)
};

Solution

  • You've misunderstood what traits => ['Array'] does. That allows you to set up handles methods. It does not allow you to call methods like push directly. You need to use Moose::Autobox for that (and you don't need the Array trait).

    Or you could do:

    has 'tid_stack' => (
        traits => ['Array'],
        is     => 'rw',
        isa    => 'ArrayRef[Str]',
        default => sub { [] },
        handles => {
          push_tid => 'push',
        },
    );
    
    ...
    
        $self->push_tid( get_hrtid( $template ) );