我正在使用 perl 语言开发模板工具包。我正在 perl 中读取 YAML 文件,我想使用模板工具包根据 yaml 值写入不同的输出文件。你能帮我解决这个问题吗
YAML 文件:test.yaml
---
constraints:
data1:
file: file1
value: 'Writing in file 1: DATA1'
data2:
file: file2
value: 'Writing in file 2: DATA2'
data3:
file: file1
value: 'Writing in file 1: DATA3'
perl 脚本:
use strict;
use warnings;
use Template;
use YAML qw(LoadFile);
use Data::Dumper;
my $tt = Template->new({
INCLUDE_PATH => './',
INTERPOLATE => 1,
}) or die "$Template::ERROR\n";
my %data = % {LoadFile('test.yaml') };
my $report;
$tt->process('test.tt', \%data, \$report) or die $tt->error(), "\n";
print $report;
test.tt:未完成仅开始
[% FOREACH a IN constraints.keys.sort %]
[% IF constraints.$a.file == 'file1' %]
constraints.$a.value > file1 --------**Need help on this**
[% ELSE %]
constraints.$a.value > file2 --------**Need help on this**
[% END %]
[% END %]
异常输出:
file1:
Writing in file 1: DATA1
Writing in file 1: DATA3
file2:
Writing in file 2: DATA2
您无法从模板中选择输出文件。
模板应该以人类可读的方式呈现(格式化)输入。您想要做的事情应该在 Perl 脚本中。
use File::Slurp;
[...]
# Loop over all constraints
for my $constraint (keys %{$data{constraints}}) {
# Render each constraint value to the specified file
my $rendered_file_content;
$tt->process(
'render_constraint.tt',
$data{constraints}->{$constraint}->{value},
\$rendered_file_content,
);
write_file(
$data{constraints}->{$constraint}->{file},
$rendered_file_content,
);
}
注意事项:
%data = % {LoadFile('test.yaml') }
通常不需要。constraints
、data
、value
等名称应替换为会说话的名称。这些名称可能只是此问题的占位符示例。在实际脚本中使用 $car_brand
代替 $value
(例如)。use FindBin qw( $RealBin );
use Template qw( );
use YAML qw( LoadFile );
my $data = LoadFile( 'test.yaml' );
my $tt = Template->new({
INCLUDE_PATH => $RealBin,
INTERPOLATE => 1,
});
for my $constraint_id ( sort keys $data->{ constraints }->%* ) {
my $constraint = $data->{ constraints }{ $constraint_id };
my $qfn = "$RealBin/$constraint->{ file }";
open( my $fh, ">>", $qfn )
or die( "Can't create `$qfn` or open for append: $!\n");
my %vars = (
value => $constraint->{ value },
);
$tt->process( 'test.tt', \%vars, $fh )
or die( $tt->error(), "\n" );
}
[% value %]