Text::Template question

Discussion in 'Perl Misc' started by Phil Lawrence, May 25, 2007.

  1. 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:
     
    Phil Lawrence, May 25, 2007
    #1
    1. Advertisements

  2. Phil Lawrence

    Paul Lalli Guest

    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
     
    Paul Lalli, May 25, 2007
    #2
    1. Advertisements

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 (here). After that, you can post your question and our members will help you out.
Similar Threads
Loading...