我可以在Perl中动态指定的类中访问静态方法吗? [英] Can I access a static method in a dynamically specified class in Perl?

查看:87
本文介绍了我可以在Perl中动态指定的类中访问静态方法吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以在Perl中动态指定一个类并在该类中访问静态方法?这不起作用,但是说明了我想做的事情:

Is it possible to dynamically specify a class in Perl and access a static method in that class? This does not work, but illustrates what I'd like to do:

    use Test::Class1;  
    my $class = 'Test::Class1';  
    $class::static_method();    

我知道我可以做到:

    $class->static_method();  

并忽略传递给static_method的类名,但是我想知道是否有更好的方法.

and ignore the class name passed to static_method, but I wonder if there's a better way.

推荐答案

是的!严格执行此操作的方法是使用 can .

Yup! The way to do it with strictures is to use can.

package Foo::Bar;
use strict;
use warnings;

sub baz
{
   return "Passed in '@_' and ran baz!";
}

package main;
use strict;
use warnings;

my $class = 'Foo::Bar';

if (my $method = $class->can('baz'))
{
   print "yup it can, and it ";
   print $method->();
}
else
{
   print "No it can't!";
}

can返回对该方法的引用,即undef/false.然后,您只需要使用dereferene语法调用该方法即可.

can returns a reference to the method, undef / false. You then just have to call the method with the dereferene syntax.

它给出:


    > perl foobar.pl
    yup it can, and it Passed in '' and ran baz!

这篇关于我可以在Perl中动态指定的类中访问静态方法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆