[英]How do you dynamically call a method of an object?
in Perl I know you can use eval
and *{$func_name}
to call functions dynamically but how do you do this with methods of an object?在 Perl 中,我知道您可以使用
eval
和*{$func_name}
来动态调用函数,但是如何使用对象的方法来执行此操作?
for example例如
EZBakeOven
sub make_Cake { ... }
sub make_Donut { ... }
sub make_CupCake { ... }
sub make_Soup { ... }
sub make{
my($self,$item) = @_;
if( defined $self->make_$item ){ #call this func if it exists
$self->make_$item( temp => 300, with_eggs => true );
}
}
so that if I say something like所以如果我说类似的话
$self->make('Cake');
#or maybe I have to use the full method name
$self->make('make_Cake');
it will call它会打电话
$self->make_Cake();
You should be able to do something like:您应该能够执行以下操作:
sub make {
my ($self, $item) = @_;
my $method = "make_$item";
$self->$method(whatever);
}
Edit: You might want to also use can()
to make sure you're calling a method that can be called:编辑:您可能还想使用
can()
来确保您正在调用一个可以调用的方法:
sub make {
my ($self, $item) = @_;
my $method = "make_$item";
if ($self->can($method)) {
$self->$method(whatever);
} else {
die "No such method $method";
}
}
Edit 2: Actually, now that I think about it, I'm not sure if you really can do that.编辑 2:实际上,现在我考虑了一下,我不确定您是否真的可以做到。 Code I've written before does something like that, but it doesn't use an object, it uses a class (so you're calling a specific function in a class).
我之前写过的代码做了类似的事情,但它不使用对象,它使用一个类(所以你在一个类中调用一个特定的函数)。 It might work as well for objects, but I can't guarantee it.
它可能也适用于对象,但我不能保证。
As by @CanSpice suggested use can
to check a methods existence in classes and objects.正如@CanSpice 建议的那样,使用
can
检查类和对象中的方法是否存在。 can
returns a reference to the method if it exists, undef otherwise.如果存在,则
can
返回对该方法的引用,否则返回 undef。 You can use the returned reference to call the method directly.您可以使用返回的引用直接调用该方法。
The following example calls the method in package/class context.以下示例调用包/类上下文中的方法。
__PACKAGE__
returns the current package/class name. __PACKAGE__
返回当前包/类名称。
if ( my $ref = __PACKAGE__->can("$method") ) {
&$ref(...);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.