#!/usr/bin/perl use strict; use warnings; use Data::Dumper; use constant { a => "b" }; my $c = { a => a }; my %d; $d{a} = a; print Dumper($c); print Dumper(\%d);
将输出
$VAR1 = { 'a' => 'b' }; $VAR1 = { 'a' => 'b' };
常量a被替换为表达式$d {a} = a和a =>的右侧. a,但不在左侧.
我知道常量是使用inlinable subs(documented here)实现的,如果子名称不是预先声明的,则子名称会评估它们的名称(documented here),但我看不出为什么在我的例子中对值进行一次计算,一次对名称在同一行代码中,特别是在散列的赋值中 – a => a可能是=>的结果如果以字母开头,则将左侧网站解释为字符串.
旁注:添加parantheses以使子调用显式生成预期结果:
# ... my $c = { a() => a }; # or my $c = { a,a }; my %d; $d{a()} = a; # ....
输出:
$VAR1 = { 'b' => 'b' }; $VAR1 = { 'b' => 'b' };
(使用perl 5.18测试的所有示例)
解决方法
You can get into trouble if you use constants in a context which automatically quotes barewords (as is true for any subroutine call). For example,you can’t say
$hash{CONSTANT}
becauseCONSTANT
will be interpreted as a string.
然后继续您找到的解决方案
Use
$hash{CONSTANT()}
or$hash{+CONSTANT}
to prevent the bareword quoting mechanism from kicking in.
然后它也将其拼写为哈希
Similarly,since the
=>
operator quotes a bareword immediately to its left,you have to sayCONSTANT() => 'value'
(or simply use a comma in place of the big arrow) instead ofCONSTANT => 'value'
.