如何确定对象是否在Perl中实现了一个方法?

cdl*_*ary 6 oop reflection polymorphism perl

我有一个实现两个(非正式)接口的多态对象数组.我希望能够通过以下方式区分它们:

if (hasattr(obj, 'some_method')) {
    # `some_method` is only implemented by one interface.
    # Now I can use the appropriate dispatch semantics.
} else {
    # This must be the other interface.
    # Use the alternative dispatch semantics.
}
Run Code Online (Sandbox Code Playgroud)

也许这样的事情有效吗?:

if (*ref(obj)::'some_method') {
    # ...
Run Code Online (Sandbox Code Playgroud)

我很难说出语法何时会尝试调用子例程以及何时返回子例程引用.我不太熟悉包装符号表ATM,我只是试图破解一些东西.:-)

提前致谢!

Ken*_*ric 16

use Scalar::Util qw(blessed);
if( blessed($obj) and $obj->can('some_method') ){ 

}
Run Code Online (Sandbox Code Playgroud)

"can"这里是UNIVERSAL所有类继承的方法.类可以覆盖此方法,但它不是一个好主意.

此外,"can"返回对函数的引用,因此您可以执行以下操作:

$foo->can('some_method')->( $foo , @args );
Run Code Online (Sandbox Code Playgroud)

要么

my $sub = $foo->can('some_method'); 
$foo->$sub( @args ); 
Run Code Online (Sandbox Code Playgroud)

编辑更新的链语法,感谢Brian Phillips