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

标签 perl roles universal

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/

相关文章:

Windows 10 UWP 应用程序 - 后退按钮仅在第二次按下时有效

perl - 如何将文本文件的每一行写入 CSV 行

Perl - 将对象的哈希值作为类中的单个对象返回

asp.net - 如何在 mysql 数据库中存储文件列表并根据用户角色显示它们

java - 根据编辑请求中的用户角色选择要使用的 pojo

c# - 我应该在 Web.config 文件中为多个页面添加多个 <location> 元素吗

c# - 最小化 Windows 10 通用时背景音频停止播放

perl - 如何处理从 `tail` 捕获的输出而不进行重新处理?

arrays - "$scalar = @array[n]"的后果是什么?

Windows 10 WebView 和 Adob​​e Flash