Dynamic function injection into Text::Template namespace

144 Views Asked by At

I am using the following syntax to inject a function into Text::Template so it knows about that function when using fill_in():

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

I noticed that if fill_in() is called more than once, that GEN0 changes to GEN1 for the subsequent call, then GEN2 ... etc.

So this only works if fill_in is called once, because only the GEN0 namespace is used.

How can I dynamically inject some_function into each used namespace? I know it's something like this, but I don't know the syntax I would use exactly:

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

    # Call fill_in here
}
2

There are 2 best solutions below

1
On BEST ANSWER

No need to guess at the internals. Use the PREPEND option:

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;

Results in:

% perl tt.pl
foo is not bar
1
On

This should work:

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
}