且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

我什么时候应该使用 &调用一个 Perl 子程序?

更新时间:2022-12-08 10:33:51

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.