我什么时候应该使用&调用Perl子例程? [英] When should I use the & to call a Perl subroutine?

查看:89
本文介绍了我什么时候应该使用&调用Perl子例程?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我听说人们不应该使用&来调用Perl订阅,即:

I have heard that people shouldn't be using & to call Perl subs, i.e:

function($a,$b,...);
# opposed to
&function($a,$b,...);

我知道参数列表是可选的,但是在什么情况下使用&是合适的,以及在某些情况下您绝对不应该使用它呢?

I know for one the argument list becomes optional, but what are some cases where it is appropriate to use the & and the cases where you should absolutely not be using it?

在省略&时,性能如何在这里发挥作用?

Also how does the performace increase come into play here when omitting the &?

推荐答案

IMO,唯一有理由使用&的唯一机会是获取或调用coderef,例如:

IMO, the only time there's any reason to use & is if you're obtaining or calling a coderef, like:

sub foo() {
    print "hi\n";
}

my $x = \&foo;
&$x();

在大多数情况下绝对不应该使用的主要时间是在调用具有指定任何非默认调用原型的子程序时行为.我的意思是,某些原型允许重新解释参数列表,例如将@array%hash规范转换为引用.因此,潜艇将期望发生这些重新解释,并且除非您进行任何必要的长度以手工模仿它们,否则潜艇将获得与预期的输入完全不同的输入.

The main time that you can use it that you absolutely shouldn't in most circumstances is when calling a sub that has a prototype that specifies any non-default call behavior. What I mean by this is that some prototypes allow reinterpretation of the argument list, for example converting @array and %hash specifications to references. So the sub will be expecting those reinterpretations to have occurred, and unless you go to whatever lengths are necessary to mimic them by hand, the sub will get inputs wildly different from those it expects.

我认为主要是人们试图告诉您您仍在以Perl 4风格进行编写,而我们现在有了一种更干净,更好的东西,称为Perl 5.

I think mainly people are trying to tell you that you're still writing in Perl 4 style, and we have a much cleaner, nicer thing called Perl 5 now.

关于性能,Perl优化了&失败的子调用的多种方式,其中之一是常量的内联.

Regarding performance, there are various ways that Perl optimizes sub calls which & defeats, with one of the main ones being inlining of constants.

在某些情况下,使用&可以带来性能上的好处:如果要转发使用foo(@_)的子调用.使用&foofoo(@_)无限快.除非您通过分析明确确定需要微优化,否则我不建议这样做.

There is also one circumstance where using & provides a performance benefit: if you're forwarding a sub call with foo(@_). Using &foo is infinitesimally faster than foo(@_). I wouldn't recommend it unless you've definitively found by profiling that you need that micro-optimization.

这篇关于我什么时候应该使用&调用Perl子例程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆