hashref查找中的语法错误,看不到为什么 [英] Syntax error in hashref lookup, can not see why
问题描述
perl -E 'say for map s/(æ|ø|å)/ {qw(æ ae ø oe å aa)}->{$1}/ger, qw(rød gul blå)'
perl -E 'say for map s/(æ|ø|å)/"".{qw(æ ae ø oe å aa)}->{$1}/ger, qw(rød gul blå)'
上面的第一行给我syntax error at -e line 1, near "}->"
,但第二行按预期打印roed
,gul
和blaa
.这是编译器的弱点吗?还是有我看不见的某些原因?我进行了测试,并在5.10、5.22和5.26版本中获得了这种行为.
The first line above gives me syntax error at -e line 1, near "}->"
but the second prints roed
, gul
and blaa
as expected. Is this a weakness of the compiler or are there some reason for it that I can't see? I tested and got this behaviour in versions 5.10, 5.22 and 5.26.
推荐答案
The {...}
are interpreted as a BLOCK, not a hashref. We can see this by adding a +
perl -E'say for map s/(æ|ø|å)/+{qw(æ ae ø oe å aa)}->{$1}/ger, qw(rød gul blå)'
现在有效,因为一元+
必须是一个表达式;因此+
消除了代码的歧义.然后,解释器继续将构造识别为匿名哈希构造器.
and now it works, since what follows the unary +
must be an expression; so +
disambiguates the code. Then the interpreter goes on to identify the construct as an anonymous hash constructor.
否则,它必须猜测{
,因为它无法解析,然后再决定是分析块还是表达式.它可以分析上下文以确定{...}
是什么,但是我认为如果仅以折衷的方式认为它太复杂,这是合理的.
Otherwise it has to guess at {
since it can't parse away before deciding whether it is parsing a block or an expression. It could analyze the context to determine what {...}
is but I'd find it reasonable if that was simply deemed much too complex as a trade off.
在另一个示例中,是由串联运算符(.
)完成的.
In the other example it is the concatenation operator (.
) that does it.
有关一元代码+
强制将以下代码视为表达式的另一个示例,以及有关相关文档的详细信息,请参见
For another example of the unary +
forcing treatment of the following code as an expression, and for details about related documentation, see this post.
这篇关于hashref查找中的语法错误,看不到为什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!