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

查看:24
本文介绍了我什么时候应该使用 &调用一个 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
";
}

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

可以在大多数情况下绝对不应该使用它的主要时间是在调用具有指定任何非默认调用的原型的子程序时行为.我的意思是一些原型允许重新解释参数列表,例如将 @array%hash 规范转换为引用.因此,sub 会期待那些重新解释的发生,除非您竭尽全力地手动模仿它们,否则 sub 将获得与其预期截然不同的输入.

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天全站免登陆