加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

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

发布时间:2020-12-15 21:22:34 所属栏目:大数据 来源:网络整理
导读:我试图在perl中使用常量值并偶然发现以下奇怪的行为: #!/usr/bin/perluse 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 = {
我试图在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'.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读