如何在Perl中调用存储在哈希中的函数名?

Eth*_*her 8 syntax perl attributes reference moose

我确定这在文档的某个地方有所涉及,但我一直无法找到它......我正在寻找能够在类名称存储在哈希中的类上调用方法的语法糖(而不是简单的标量):

use strict; use warnings;

package Foo;
sub foo { print "in foo()\n" }

package main;
my %hash = (func => 'foo');

Foo->$hash{func};
Run Code Online (Sandbox Code Playgroud)

如果我首先复制$hash{func}到标量变量,那么我可以调用Foo->$func就好......但是缺少什么来启用Foo->$hash{func}它?

(编辑:我不是要通过在类上调用一个方法来做任何特殊的事情Foo- 这可能很容易成为一个受祝福的对象(在我的实际代码中);它只是更容易编写一个自包含的使用类方法的示例.)

编辑2:为了完整性,请回答下面的评论,这就是我实际在做的事情(这是在Moose属性糖库中,用Moose :: Exporter创建的):

# adds an accessor to a sibling module
sub foreignTable
{
    my ($meta, $table, %args) = @_;

    my $class = 'MyApp::Dir1::Dir2::' . $table;
    my $dbAccessor = lcfirst $table;

    eval "require $class" or do { die "Can't load $class: $@" };

    $meta->add_attribute(
        $table,
        is => 'ro',
        isa => $class,
        init_arg => undef,  # don't allow in constructor
        lazy => 1,
        predicate => 'has_' . $table,
        default => sub {
            my $this = shift;
            $this->debug("in builder for $class");

            ### here's the line that uses a hash value as the method name
            my @args = ($args{primaryKey} => $this->${\$args{primaryKey}});
            push @args, ( _dbObject => $this->_dbObject->$dbAccessor )
                if $args{fkRelationshipExists};

            $this->debug("passing these values to $class -> new: @args");
            $class->new(@args);
        },
    );
}
Run Code Online (Sandbox Code Playgroud)

我用这个替换了上面标记的行:

        my $pk_accessor = $this->meta->find_attribute_by_name($args{primaryKey})->get_read_method_ref;
        my @args = ($args{primaryKey} => $this->$pk_accessor);
Run Code Online (Sandbox Code Playgroud)

PS.我刚刚注意到,同样的技术(使用Moose元类来查找coderef而不是假设其命名约定)也不能用于谓词,因为Class :: MOP :: Attribute没有类似的get_predicate_method_ref访问器.:(

run*_*rig 14

Foo->${\$hash{func}};
Run Code Online (Sandbox Code Playgroud)

但为了清楚起见,我可能仍然将其写成:

my $method = $hash{func};
Foo->$method;
Run Code Online (Sandbox Code Playgroud)