perl常量在哪里被它们的值替换?

前端之家收集整理的这篇文章主要介绍了perl常量在哪里被它们的值替换?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我试图在perl中使用常量值并偶然发现以下奇怪的行为:
#!/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测试的所有示例)

解决方法

constant页的末尾,即 CAVEATS,有答案

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} because CONSTANT 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 say CONSTANT() => 'value' (or simply use a comma in place of the big arrow) instead of CONSTANT => 'value'.

猜你在找的Perl相关文章