Text::Template question

P

Phil Lawrence

My first time using Text::Template... can anyone see why the vars in
my template are not being filled in?

$ cat foo.tmpl
foo: [@-- $foo --@]

$ cat foo.pl
#!/usr/local/bin/perl
use warnings;
use strict;
use diagnostics;

use Text::Template;

my $foo = 'FOO_BAR';

my $template = Text::Template->new(
DELIMITERS => [ '[@--', '--@]' ],
TYPE => 'FILE',
SOURCE => 'foo.tmpl'
);
print $template->fill_in();

$ ./foo.pl
foo:
 
P

Paul Lalli

My first time using Text::Template... can anyone see why the vars in
my template are not being filled in?

$ cat foo.tmpl
foo: [@-- $foo --@]

$ cat foo.pl
#!/usr/local/bin/perl
use warnings;
use strict;
use diagnostics;

use Text::Template;

my $foo = 'FOO_BAR';

my $template = Text::Template->new(
DELIMITERS => [ '[@--', '--@]' ],
TYPE => 'FILE',
SOURCE => 'foo.tmpl'
);
print $template->fill_in();

$ ./foo.pl
foo:

Your template does not have access to lexical variables (ie, variables
declared with 'my'). This is stated in Text::Template's documentation
at http://search.cpan.org/~mjd/Text-Template-1.44/lib/Text/Template.pm#my_variables

You have a few options:
1) Declare the variable with 'our' instead of 'my'. That will make it
a global variable in the current package. Note the danger of this -
if your template changes the variable, it's changed in your perl code
as well.
2) Use a variable in a different package, and pass that package to
your Text::Template fill_in method. For example, rather than
my $foo = 'FOOBAR';
you'd have:
$TEMPLATE::foo = 'FOOBAR';
and then pass PACKAGE => 'TEMPLATE' as an argument to fill_in
3) Pass a hash ref of values to the fill_in method. So keep your
my $foo = 'FOOBAR';
and pass HASH => { foo => $foo } as an argument to fill_in

Hope this helps,
Paul Lalli
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,012
Latest member
RoxanneDzm

Latest Threads

Top