gpt4 book ai didi

perl - 将局部变量合并到 perl 中的全局哈希中

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

我需要在多个用户哈希中加入通用哈希(宏)。实际上,这些都是用 perl 编写的 HoH/HoL 规范。

我希望“用户”规范采用带有自己修改的宏规范。在下面的示例中,变量“$v_Y”需要在用户 1 和用户 2 中具有不同的值。

我下面的内容不完全是代码,而是试图说明问题。由于 macro_spec 已经创建,我无法拥有 $v_Y 的多个值。

## this is in a package
my $MACRO_SPEC = {
mkeyX => "value_X",
mkeyY => $v_Y,
};

#this is USER1 package,
$v_Y = "U1_VALUE_X";
# use MACRO_SPEC
my $USER1 = (
u1key1 => "u1value1", u1macrokey => $MACRO_SPEC, # need macro to interpolate 'local' $v_Y
);

#this is USER2 package,
$v_Y = "U2_VALUE_X";
# use MACRO_SPEC
my $USER2 = (
u2key1 => "u2value1",
u2macrokey => $MACRO_SPEC, # need macro to interpolate 'local' $v_Y
);


#this is how USER1 should look after the interpolation
my $USER1 = (
u1key1 => "u1value1",
u1macrokey => {
mkeyX => "value_X",
mkeyY => "U1_VALUE_X"
},
);
#this is how USER2 should look after the interpolation
my $USER2 = (
u2key1 => "u2value1",
u1macrokey => {
mkeyX => "value_X",
mkeyY => "U2_VALUE_X"
},
);

最佳答案

就像 melpomene 所建议的那样,您希望 $MACRO_SPEC 成为一个函数,每次调用它时都可以生成不同的东西。

package One;
our $v_Y;
my $MACRO_SPEC = sub { +{ mkeyX => "value_X", mkeyY => $v_Y } };

...

package USER1;
$One::v_Y = "U1_VALUE_X";
my $user1 = { # { }, not ( ), to define a hash reference
u1key1 => "u1value1",
u1macrokey => $MACRO_SPEC->(), # $f->() to exec code defined in $f
...
};

关于perl - 将局部变量合并到 perl 中的全局哈希中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41360720/

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