2

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
}
DVK
  • 126,886
  • 32
  • 213
  • 327
cgsd
  • 1,242
  • 2
  • 13
  • 25

2 Answers2

4

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
Diab Jerius
  • 2,310
  • 13
  • 18
  • Thanks! Another reason it is necessary to do like this is because simply prepending the whole sub `sub my_sub {...}` causes all sorts of `sub already defined` errors because Text::Template has no option to append something only once. Seems like quite an oversight, unless I've missed it... – Nate Glenn Feb 06 '15 at 09:57
3

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
}
DVK
  • 126,886
  • 32
  • 213
  • 327
  • 3
    I kept your `foreach` structure, but you can also replace it with `foreach my $i (0 .. $#items)` instead, so as to not keep a separate counter – DVK Dec 10 '14 at 23:49