Syntax error in hashref lookup, can not see why

你离开我真会死。 提交于 2021-02-09 07:25:58

问题


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å)'

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.


回答1:


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.



来源:https://stackoverflow.com/questions/57784193/syntax-error-in-hashref-lookup-can-not-see-why

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!