10, p2 => 20); while ( ($k,$v) = each %x ) { print \"key $k v-6ren">
gpt4 book ai didi

Perl:在这种特殊情况下,哈希不允许使用字母数字键

转载 作者:行者123 更新时间:2023-12-03 18:39:48 27 4
gpt4 key购买 nike

我通过创建哈希发现了一个奇怪的行为:

perl -e "%x = (1 => 10, p2 => 20); while ( ($k,$v) = each %x ) { print \"key $k value $v\n\";}"
给出以下输出:
key p2 value 20
key 1 value 10
但是,如果我将 key p2 更改为 1p2,则会出现错误:
perl -e "%x = (1 => 10, 1p2 => 20); while ( ($k,$v) = each %x ) { print \"key $k value $v\n\";}"
输出是:
syntax error at -e line 1, near "1p2"
Execution of -e aborted due to compilation errors.
为什么会报错?
(Win10,草莓Perl v5.30.0)

最佳答案

引用 perlop (强调):

The "=>" operator (sometimes pronounced "fat comma") is a synonym for the comma except that it causes a word on its left to be interpreted as a string if it begins with a letter or underscore and is composed only of letters, digits and underscores. This includes operands that might otherwise be interpreted as operators, constants, single number v-strings or function calls. If in doubt about this behavior, the left operand can be quoted explicitly.


由于 1p2 以数字开头,因此 => 的特殊行为不适用。您必须像普通字符串一样引用它以防止解析错误。

关于Perl:在这种特殊情况下,哈希不允许使用字母数字键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63882357/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com