DOES( ROLE-6ren">
gpt4 book ai didi

perl - UNIVERSAL 中 "ROLE"的定义是什么,Perl 角色如何工作?

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

Perl 有一个名为 UNIVERSAL 的内部伪模块。所有模块都继承自它。它有一个名为 DOES 的方法。 , 来自 the docs on UNIVERSAL .

$obj->DOES( ROLE )

CLASS->DOES( ROLE )

DOES checks if the object or class performs the role ROLE. A role is a named group of specific behavior (often methods of particular names and signatures), similar to a class, but not necessarily a complete class by itself. For example, logging or serialization may be roles.

DOES and isa are similar, in that if either is true, you know that the object or class on which you call the method can perform specific behavior. However, DOES is different from isa in that it does not care how the invocand performs the operations, merely that it does. (isa of course mandates an inheritance relationship. Other relationships include aggregation, delegation, and mocking.)

There is a relationship between roles and classes, as each class implies the existence of a role of the same name. There is also a relationship between inheritance and roles, in that a subclass that inherits from an ancestor class implicitly performs any roles its parent performs. Thus you can use DOES in place of isa safely, as it will return true in all places where isa will return true (provided that any overridden DOES and isa methods behave appropriately).



我知道 Moose 等人提供了 DOES ,并且我了解如何使用它。 但在 UNIVERSAL::DOES 的意义上什么是 ROLE ?他们是如何被追踪的?它们是如何创建的 除了驼鹿满足 DOES ?我尝试查看源代码,但 the implementation of DOES was not provided .这是 ROLE 的概念吗? CORE 中的某些内容珀尔?这似乎与 perldoc perlapi 's mention of sv_does_sv (also sv_does / sv_does_pv ) 有关

sv_does_sv Returns a boolean indicating whether the SV performs a specific, named role. The SV can be a Perl object or the name of a Perl class.

bool sv_does_sv(SV* sv, SV* namesv, U32 flags)



我可以看到对 sv_does_sv 的调用在 implementation of universal.c . SV 角色的定义是什么?我在哪里可以找到有关此的更多信息?

从用户层面来看,这里的代码是做什么的,(这是一个子引用)
UNIVERSAL->can('DOES')

返回的地址与 UNIVERSAL->can('isa') 不同在同一个调用中,所以它做了一些不同的事情,我可以在上面链接的 universal.c 中看到那个渣滓.

最佳答案

UNIVERSAL::DOES相当于:

sub DOES {
croak "Usage: invocant->DOES(kind)"
if @_ != 2;
$_[0]->isa($_[1]);
}

在内部, sv_does_sv调用 isa第一个 SV 上的方法通过它。 perl 本身不提供角色的实现,所以留给角色模块来提供 DOES这说明了他们。

Moose、Moo、Role::Tiny、Mouse 等中的约定是 DOES方法对于类及其父类以及类及其父类所组成的角色都是正确的。这些库还提供 does方法,仅适用于类及其父类的组合角色,而不适用于类或其父类。

关于perl - UNIVERSAL 中 "ROLE"的定义是什么,Perl 角色如何工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57959140/

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