从函数返回perl中的+ {}或{}与返回ref或value之间的区别 [英] Difference between returning +{} or {} in perl from a function, and return ref or value

查看:87
本文介绍了从函数返回perl中的+ {}或{}与返回ref或value之间的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚开始在一个新团队的新地方工作.他们告诉我我们在perl模块中返回ref而不是值.我也看到类似return +{foo=>'bar'}; and return {foo=>'bar'};的东西吗?以及是否返回ref或value?

I just started work with a new team new place. They told me we return ref instead of value in our perl modules. Also I saw something like return +{foo=>'bar'}; and return {foo=>'bar'}; Whats the difference? And whether to return ref or value?

推荐答案

return +{foo=>'bar'}中的+完全没有用.

首先,了解一些背景.

Perl语言有歧义.举个例子

The Perl language has ambiguities. Take for example

sub f {
   {  }     # Is this a hash constructor or a block?
}

{ }是块(裸循环")的有效语法.
{ }是哈希构造函数的有效语法.
两者都可以作为声明!

{ } is valid syntax for a block ("bare loop").
{ } is valid syntax for a hash constructor.
And both are allowed as a statement!

因此Perl必须猜测. Perl通常猜测正确,但并非总是如此.您可以给它提示".一元-+可用于执行此操作.一元-+是完全透明的运算符;它什么都不做.但是,必须在其后跟随一个表达式(而不是语句). { }作为表达式只有一种可能的含义.

So Perl has to guess. Perl usually guesses correctly, but not always. You can give it "hints". Unary-+ can be used to do this. Unary-+ is a completely transparent operator; it does nothing at all. However, it must be followed by an expression (not a statement). { } has only one possible meaning as an expression.

+{ }   # Must be a hash constructor.

类似地,您可以欺骗Perl进行另一种猜测.

Similarly, you can trick Perl to guess the other way.

{; }   # Perl looks ahead, and sees that this must be a block.

以下是Perl猜错的示例:

Here's an example where Perl guesses wrong:

map { {} } 1..5   # ok. Creates 5 hashes and returns references to them.
map {}, 1..5      # XXX Perl guesses you were using "map BLOCK LIST".
map +{}, 1..5     # ok. Perl parses this as "map EXPR, LIST".


对于问题中的代码,return必须后跟一个表达式(如果有的话),因此对于return { ... };仅有一种可能的解释,因此+在那里完全没有用.


As for the code in the question, return must be followed by an expression (if anything), so there's only one possible interpretation for return { ... };, so the + is completely useless there.

大多数人仅在必要时才消除歧义.其他人可能会在+含糊不清时添加它(即使Perl猜对了).但这是我第一次听说在每个哈希构造函数之前使用+.

Most people only disambiguate when necessary. Others might add + whenever it's ambiguous (even if Perl would guess right). But this is the first time I've heard of using + in front of every hash constructor.

这篇关于从函数返回perl中的+ {}或{}与返回ref或value之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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