我可以在perl中传递对象方法的代码参考吗?
在一个网络处理程序中,处理各种参数以获取和设置我正在大量使用。 我有一个子例程,可以接收封闭,并使用返回时作为参数传递的另一个闭合(听起来很复杂,但这只是我想要这样的为什么)。 现在,我有一种情况,我必须通过两个非常相似的封闭,每个封闭情况使用相同的对象方法,但使用不同的参数(对象方法检查传递的参数数)。
我的想法不是通过两个(或更多)类似的封闭,而是将参考$ meth_ref
传递给对象的方法(对象也传递给函数返回闭合),以便该函数可以使用代码参考传递不同参数。
不幸的是,我没有发现语法这样做。
代码草图:
sub closure_maker($$)
{
my ($obj, $meth_ref) = @_;
return sub (...) {
$meth_ref->($obj);
...
$meth_ref->($obj, ...);
};
}
my @handlers = (closure_maker($obj1, ???), closure_maker($obj2, ???));
希望您明白。
In a network handler dealing with various parameters to get and set I'm using closures heavily.
I have a subroutine that receives a closure and builds another closure using that passed as parameter on return (Sounds complicated, but that's just why I want such).
Now I have a case where I would have to pass two very similar closures, each using the same object method, but with different parameters (the object method checks the number of parameters passed).
My idea was not to pass two (or more) similar closures, but pass a reference $meth_ref
to the object's method (the object is also passed to the function returning closures), so that the function can use the code reference to pass varying parameters.
Unfortunately I didn't find out the syntax to do so.
Code sketch:
sub closure_maker($)
{
my ($obj, $meth_ref) = @_;
return sub (...) {
$meth_ref->($obj);
...
$meth_ref->($obj, ...);
};
}
my @handlers = (closure_maker($obj1, ???), closure_maker($obj2, ???));
I hope you get the idea.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
使用
$ obj--> $ method_name()
。您可以使用
$ obj->可以
获得对该方法的引用。Use
$obj->$method_name()
.You can use
$obj->can
to obtain a reference to the method.您可以获取对
\& className ::方法
的参考,然后可以与该类的给定对象一起使用。例如:输出
如果您是偏执的,则可能需要在方法中添加类型检查,以确保它们不会意外地使用错误类的对象调用。
ISA
运算符,在Perl 5.32中添加,使其简单:旧版本可以使用内置
isa
方法:You can get a reference to a method with
\&Classname::method
that can then be used with a given object of that class. For example:outputs
If you're paranoid, you might want to add type checking to the methods to make sure they're not accidentally called with an object of the wrong class. The
isa
operator, added in perl 5.32, makes this easy:Older versions can use the built-in
isa
method:我找到了一个确实很丑陋的解决方案,但它起作用。
示例会话来自真实代码:
在绘制的解决方案中,我不必知道(并明确写下)所使用的每个对象的类。
I found a solution that is really ugly, but it works.
The sample session is from the real code:
In the solution sketched I don't have to know (and write down explicitly) the class of each object being used.