如何使用鼠标委托数组的第一个元素?

发布于 2024-12-13 07:22:08 字数 534 浏览 3 评论 0原文

我有一个包含一堆对象的对象。该对象表示当前状态,堆栈中的每个对象都保存特定嵌套级别的状态。

package State;

use Mouse;
use RealState;

has state_stack => {
    is    => 'rw',
    isa   => 'ArrayRef[RealState]',
    default => sub {
        return [RealState->new]
    }
};

我希望 State 委托给 State->state_stack->[0]。我怎样才能用鼠标有效地做到这一点(所以没有元黑客攻击)。我无法使用 Moose,我的项目 不能有任何依赖项(我正在捆绑 Mouse::Tiny) 。

“你不能”没关系,我会写一个AUTOLOAD

I have an object which holds a stack of objects. The object represents the current state, and each object in the stack holds the state at a particular level of nesting.

package State;

use Mouse;
use RealState;

has state_stack => {
    is    => 'rw',
    isa   => 'ArrayRef[RealState]',
    default => sub {
        return [RealState->new]
    }
};

I want State to delegate to State->state_stack->[0]. How can I do that efficiently with Mouse (so no meta hacking). I cannot use Moose, my project cannot have any dependencies (I'm bundling Mouse::Tiny).

"You can't" is fine, I'll write an AUTOLOAD.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(1

爱你不解释 2024-12-20 07:22:08

你不能直接这样做,但有一个比自动加载更好的技巧。也就是说,RealState->meta->get_all_method_names() 为您提供 RealState 中定义的方法名称。

#!perl
use 5.14.0;
package RealState {
    use Mouse;

    sub foo { 'foo' }
    __PACKAGE__->meta->make_immutable;
}
package State {
    use Mouse;

    has stack => (
        is => 'rw',
        isa => 'ArrayRef',
        default => sub { [ RealState->new ] },
    );

    # define delegates for stack->[0]
    my $meta = __PACKAGE__->meta;
    foreach my $name(RealState->meta->get_all_method_names) {
        next if Mouse::Object->can($name); # avoid 'new', 'DESTROY', etc.

        # say "delegate $name";
        $meta->add_method($name => sub {
            my $self = shift;
            $self->stack->[0]->$name(@_);
        });
    }

    $meta->make_immutable;
}

my $state = State->new();
say $state->foo();

You can't it directly, but there's a hack better than AUTOLOAD. That is, RealState->meta->get_all_method_names() gives you method names which are defined in RealState.

#!perl
use 5.14.0;
package RealState {
    use Mouse;

    sub foo { 'foo' }
    __PACKAGE__->meta->make_immutable;
}
package State {
    use Mouse;

    has stack => (
        is => 'rw',
        isa => 'ArrayRef',
        default => sub { [ RealState->new ] },
    );

    # define delegates for stack->[0]
    my $meta = __PACKAGE__->meta;
    foreach my $name(RealState->meta->get_all_method_names) {
        next if Mouse::Object->can($name); # avoid 'new', 'DESTROY', etc.

        # say "delegate $name";
        $meta->add_method($name => sub {
            my $self = shift;
            $self->stack->[0]->$name(@_);
        });
    }

    $meta->make_immutable;
}

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