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

标签 perl hash quoting

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

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/

相关文章:

c# - 加密密码的最佳方法是什么?

linux - 在 suse linux 中远程启用和禁用 cronjob

mysql - MySQL 是否比 PostgreSQL(在 Perl/DBI 下)更能抵抗 SQL 注入(inject)攻击?

python - 如何在 python 中生成与操作系统无关的文件哈希?

perl - Devel::Peek 输出结果为 STDERR

ruby - 按周/月/年对日期进行分组哈希

python - Pandas .to_csv(文件名,引用=csv.QUOTE_NONE ERRORTypeError : to_csv() got an unexpected keyword argument 'quoting'

javascript - 如何获取JavaScript当前的工作目录?

perl - 如何在实现 net-snmp 代理时清除 perl 脚本错误?