gpt4 book ai didi

perl - 动态函数注入(inject)到 Text::Template 命名空间

转载 作者:行者123 更新时间:2023-12-02 07:26:50 25 4
gpt4 key购买 nike

我正在使用以下语法将函数注入(inject) Text::Template 所以它在使用 fill_in() 时知道该功能:

*Text::Template::GEN0::some_function = *SomeLibrary::some_function;

我注意到如果 fill_in()被多次调用,GEN0 更改为 GEN1 以进行后续调用,然后 GEN2 ... 等等。

所以这只适用于 fill_in被调用一次,因为只使用了 GEN0 命名空间。

如何将 some_function 动态注入(inject)每个使用的命名空间?我知道它是这样的,但我不知道我将使用的语法:
my $i = 0;
foreach my $item (@$items) {
# *Text::Template::GEN{i}::some_function = *SomeLibrary::some_function;
$i++;

# Call fill_in here
}

最佳答案

无需猜测内部结构。使用 PREPEND选项:

use strict;
use warnings;

use Text::Template;

sub MyStuff::foo { 'foo is not bar' };

my $tpl = Text::Template->new(
TYPE => 'STRING',
SOURCE => "{ foo() }\n",
PREPEND => '*foo = \&MyStuff::foo',
);


print $tpl->fill_in;

结果是:
% perl tt.pl
foo is not bar

关于perl - 动态函数注入(inject)到 Text::Template 命名空间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27411956/

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