Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/perl/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Perl 将动态函数注入Text::Template命名空间_Perl_Texttemplate - Fatal编程技术网

Perl 将动态函数注入Text::Template命名空间

Perl 将动态函数注入Text::Template命名空间,perl,texttemplate,Perl,Texttemplate,我使用以下语法将函数注入,以便在使用fill_in()时了解该函数: 我注意到,如果多次调用fill_in(),则第0代会在后续调用中更改为第1代,然后第2代会。。。等等 因此,这仅在调用一次fill_in时有效,因为只使用GEN0名称空间 如何在每个使用的名称空间中动态注入一些函数?我知道是这样的,但我不知道我会使用什么语法: my $i = 0; foreach my $item (@$items) { # *Text::Template::GEN{i}::some_function

我使用以下语法将函数注入,以便在使用
fill_in()
时了解该函数:

我注意到,如果多次调用
fill_in()
,则第0代会在后续调用中更改为第1代,然后第2代会。。。等等

因此,这仅在调用一次
fill_in
时有效,因为只使用GEN0名称空间

如何在每个使用的名称空间中动态注入一些函数?我知道是这样的,但我不知道我会使用什么语法:

my $i = 0;
foreach my $item (@$items) {
    # *Text::Template::GEN{i}::some_function = *SomeLibrary::some_function;
    $i++;

    # Call fill_in here
}
这应该起作用:

my $i = 0;
foreach my $item (@$items) {
    my $str = "Text::Template::GEN${i}::some_function";
    no strict "refs";
    *$str = *SomeLibrary::some_function; 
    *$str if 0; # To silence warnings
    use strict "refs" 
    $i++;

    # Call fill_in here
}

不需要猜测内部结构。使用以下选项:

结果:

% perl tt.pl
foo is not bar

我保留了您的
foreach
结构,但您也可以将其替换为
foreach my$I(0..$#items)
,以免保留单独的反感谢!必须这样做的另一个原因是,简单地在整个sub
sub my_sub{…}
前面加上前缀会导致各种各样的
sub已定义的
错误,因为Text::Template没有只附加一次的选项。似乎是个疏忽,除非我错过了。。。
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