Perl:哈希在这种特殊情况下不允许使用字母数字键
Perl: hash does not allow alphanumeric keys in this special case
我通过创建散列发现了一个奇怪的行为:
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
但是,如果我将密钥 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)
你应该做
perl -e '%x = ("1" => 10, "1p2" => 20); while ( ($k,$v) = each %x ) { print "key $k value $v\n";}'
引用散列的键
引用自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 -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
但是,如果我将密钥 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)
你应该做
perl -e '%x = ("1" => 10, "1p2" => 20); while ( ($k,$v) = each %x ) { print "key $k value $v\n";}'
引用散列的键
引用自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
以数字开头,因此 =>
的特殊行为不适用。您必须像普通字符串一样引用它以防止解析错误。