Perl 使用 coderef 作为子例程的参数
我有以下子例程:
sub my_sub {
my $coderef = shift;
$coderef->();
}
sub coderef {
my $a = shift;
my $b = shift;
print $a+$b;
}
并且想要以这种方式调用 my_sub(\coderef($a,$b)) 即我想提供代码引用的参数并在my_sub 函数。在perl中可以做这样的事情吗?
I have the following subroutines:
sub my_sub {
my $coderef = shift;
$coderef->();
}
sub coderef {
my $a = shift;
my $b = shift;
print $a+$b;
}
and want to call my_sub(\coderef($a,$b))
in this manner i.e I want to provide the arguments of the code ref with it and run it on the my_sub function. Is it possible to do something like this in perl?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
如果从表面上看这些潜艇,那么
my_sub
不会做任何事情。这里发生了两件事:
定义 coderef
使用必要的参数执行它
假设
my_sub
是某种函子,并将 coderef 作为其第一个参数传递:If those subs are to be taken at face value,
my_sub
isn't doing anything.There are two things going on here:
Define the coderef
Execute it with the necessary parameters
Assuming
my_sub
is some kind of a functor that is passed the coderef as its first argument:如果我正确理解您的问题,您需要将对
coderef
子例程的调用包装在另一个匿名子例程中,如下所示:If I understand your question correctly, you need to wrap the call to your
coderef
subroutine in another anonymous subroutine, like so:这是你想要的吗?
Is this what you want?
使用匿名子例程。
Use an anonymous subroutine.
另一个想法。也许闭包可以解决您的问题?如果您将
coderef
编写为工厂,那么您可以像这样编写代码:OUTPUT
Another idea. Perhaps a closure solves your problem? If you write
coderef
as a factory then you can code like this:OUTPUT