问题
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