frazap has asked for the wisdom of the Perl Monks concerning the following question:
file data.var
fields: value pos template: mytemplate_french.tmpl mytemplate_german.tmpl value: the value of pos pos: 3
File mytemplate_french.tmpl
C'est un exemple: {$value} est {$pos}
and the code, calls with code.pl data.var
use strict; use Text::Template; use Config::YAML::Tiny; my @files = map glob($_), @ARGV; my $usage = <<EOF; usage: $0 *.var usage: $0 un.var deux.var ... EOF die $usage unless @files; foreach my $f (@files) { my $config = Config::YAML::Tiny->new( config => $f ); my @template_files = split( / /, $config->get_template ); foreach my $tf (@template_files) { my @fields = split( / /, $config->get_fields ); my $template = Text::Template->new( TYPE => 'FILE', SOURCE => $tf, ', ) or die "Couldn't construct template: $Text::Template::ERROR" +; my %data; for my $f (@fields) { $data{$f} = $config->{$f}; } my $result = $template->fill_in( HASH => \%data); # mytemplate_french.tmpl -> mytemplate_french.txt $tf=~s/\.tmpl//; open( my $out_file, ">$tf.txt" ); if ( defined $result ) { print $out_file $result; print "$tf.txt\n"; } else { print $Text::Template::ERROR; } close $out_file; } }
I would try to catch error in the template where a variable name is misspelled ($ops instead of $pos) and I tried
... my @fields = split( / /, $config->get_fields ); my @vars = map {'$' . $_} @fields; my $str_var = join(" ", @vars); my $template = Text::Template->new( TYPE => 'FILE', SOURCE => $tf, PREPEND => 'use strict; use vars eval($str_var); ', ) or die "Couldn't construct template: $Text::Template::ERROR";
But this does not work since eval is not run in my main package.
This work:But I would like to have something more flexible, since my var files won't have alway the same variable/field names.my $template = Text::Template->new( TYPE => 'FILE', SOURCE => $tf, PREPEND => 'use strict; use vars qw($value $pos); ',
Is that possible ?
Thanks
F.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Text::Template and delayed use vars
by frazap (Monk) on May 04, 2018 at 11:50 UTC |