我确定这在某处的文档中有所介绍,但我一直无法找到它......我正在寻找可以调用名称存储在哈希中的类上的方法的语法糖(而不是一个简单的标量):
use strict; use warnings;
package Foo;
sub foo { print "in foo()\n" }
package main;
my %hash = (func => 'foo');
Foo->$hash{func};
如果我首先复制$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);
},
);
}
我已经用这个替换了上面的标记行:
my $pk_accessor = $this->meta->find_attribute_by_name($args{primaryKey})->get_read_method_ref;
my @args = ($args{primaryKey} => $this->$pk_accessor);
PS。我刚刚注意到,同样的技术(使用 Moose 元类来查找 coderef 而不是假设其命名约定)也不能用于谓词,因为Class::MOP::Attribute没有类似的get_predicate_method_ref访问器。:(