Perl常数在哪里被其值替换? [英] Where are perl constants replaced by their values?

查看:54
本文介绍了Perl常数在哪里被其值替换?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在perl中使用常量值,偶然发现以下奇怪的行为:

I tried to use constant values in perl and stumbled upon the following weird behaviour:

#!/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 ,但不在左侧。

The constant a was replaced on the right hand side of the expressions $d{a} = a and a => a, but not on the left side.

我知道常量是使用inlinable subs实现的(在此处记录),并且如果未预先声明,则子名称将根据其名称求值(在此处记录),但是我看不出在我的示例中 a 进行评估的原因在同一行代码中,一次是值,一次是名称,尤其是在散列分配中- a => a 可能是 => 将左位置解释为字符串(如果它以字母开头)的结果。

I know that constants are implemented using inlinable subs (documented here) and that sub names evaluate to their names if they aren't predeclared (documented here), but I can see no reason why in my example a evaluates once to the value and once to the name in the same line of code, especially in the assignment to the hash - The a => a might be a consequence of => interpreting the left site as a string if it begins with a letter.

边注:添加括号使子调用显式产生预期结果:

Sidenote: Adding parantheses to make the sub-call explicit yields the expected result:

# ...
my $c = { a() => a }; # or my $c = { a, a };
my %d;
$d{a()} = a;
# ....

输出:

$VAR1 = {
          'b' => 'b'
        };
$VAR1 = {
          'b' => 'b'
        };

(所有示例均经过perl 5.18测试)

(all examples tested with perl 5.18)

推荐答案

constant 页的结尾洞穴,答案

如果在自动引述裸词的上下文中使用常量,可能会遇到麻烦(对于任何子例程调用都是如此)。例如,您不能说 $ hash {CONSTANT} ,因为 CONSTANT 将被解释为字符串。

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.

然后继续使用找到的解决方案

It then proceeds with the solution you found


使用 $ hash {CONSTANT()} $ hash {+ CONSTANT} 来防止裸词引用机制

Use $hash{CONSTANT()} or $hash{+CONSTANT} to prevent the bareword quoting mechanism from kicking in.

然后也将其拼写为散列


类似地,由于 => 运算符在其左侧立即引用了一个裸字,因此您必须说 CONSTANT() => ‘value’(或只是用逗号代替大箭头),而不是 CONSTANT => ‘值’

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常数在哪里被其值替换?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆