如何为 Moose 类型特征实现新句柄?

发布于 2024-12-08 04:12:05 字数 997 浏览 0 评论 0原文

假设我想将 say 功能添加到 String (注意:这是一个比现实更简单的示例)。所以我可以拥有

has foo => (
   isa => 'Str',
   traits => [ 'String' ],
   handles => {
     say_foo => 'say',
   }
);

我当然可以用来做的事情。

$self->foo( 'bar' );

$self->say_foo;

这会从字面上打印

'bar\n'

我想象子例程会是这样的

sub _say_attr {
   my ( $self, $attr ) = @_;
   say $attr;
}

任何人都可以帮助我填补我如何实际实现这个的空白吗?我并没有真正看到太多关于如何编写自己的句柄的文档。

我真的不需要知道如何修改 String 特征。尽管我希望能够拥有一个通用处理程序,但我不需要知道当前属性的名称即可使其工作。

has foo => (
    isa => 'Str',
    traits => [ 'PrintString' ],
     handles => {
         say_foo => 'say',
     }
);
has bar => (
    isa => 'Str',
    traits => [ 'PrintString' ],
     handles => {
         say_bar => 'say',
     }
);

所以 say 这里可能是一个函数的标识符,该函数不需要调用它的属性的硬编码名称。

Lets's say I wanted to add say functionality to String ( note: this is a more simple example than reality ). So I could have

has foo => (
   isa => 'Str',
   traits => [ 'String' ],
   handles => {
     say_foo => 'say',
   }
);

which I then of course would be able to use to do.

$self->foo( 'bar' );

$self->say_foo;

which would print literally

'bar\n'

I imagine the subroutine would be something like this

sub _say_attr {
   my ( $self, $attr ) = @_;
   say $attr;
}

Can anyone help me fill in the gaps on how I might actually implement this? I don't really see much in the way of documentation on how to write your own handles.

I don't really need to know how to modify the String traits. So much as I want to be able to have a generic handler, where I don't need to know the name of the current attribute in order to make it work.

has foo => (
    isa => 'Str',
    traits => [ 'PrintString' ],
     handles => {
         say_foo => 'say',
     }
);
has bar => (
    isa => 'Str',
    traits => [ 'PrintString' ],
     handles => {
         say_bar => 'say',
     }
);

so say here is probably an identifier for a function which does not need a hardcoded name of an attribute which is calling it.

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

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

发布评论

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

评论(1

被翻牌 2024-12-15 04:12:05

您真的想将 say 添加到 String 中,还是满足于将 say_foo 添加到 foo 中?

后者很简单:

has foo => (
   isa => 'Str',
   traits => [ 'String' ],
   handles => {
     say_foo => sub { say $_[0]->foo; },
   }
);

如果您想要更通用的解决方案,您应该查看 Moose::Meta::Attribute::Native::Trait::String 并复制/包装/子类化它而不是试图改变它。

Do you really want to add say to String, or would you be content with adding say_foo to foo?

The latter is easy:

has foo => (
   isa => 'Str',
   traits => [ 'String' ],
   handles => {
     say_foo => sub { say $_[0]->foo; },
   }
);

If you wanted to a more general solution, You should look at Moose::Meta::Attribute::Native::Trait::String and copy/wrap/subclass it rather than trying to change it.

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