gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 05:36:46 25 4
gpt4 key购买 nike

我试过 use constant 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} = aa => a ,但不在左侧。

我知道常量是使用可内联的 subs ( documented here ) 实现的,并且如果它们没有预先声明 ( documented here ),则子名称评估为它们的名称,但我看不出为什么在我的示例中的原因 a在同一行代码中对值进行一次计算,对名称进行一次计算,尤其是在对散列的赋值中 - a => a可能是 => 的结果如果左侧站点以字母开头,则将其解释为字符串。

旁注:添加括号使子调用显式产生预期结果:
# ...
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 - perl 常量在哪里被它们的值替换?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41094827/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com