[英]Perl simple XML template from core modules only?
通过使用带有eval evaluate /ee
修饰符的替换s///
运算符,您可以创建非常简单的东西。
像这样的东西
use strict;
use warnings;
my $template = <<'END';
<file>
<state>$state</state>
<timestamp>$time</timestamp>
<location>$location</location>
</file>
END
my $state = 'Oregon';
my $time = '10:04';
my $location = 'Salem';
(my $output = $template) =~ s{(\$\w+)}{ $1 }eeg;
print $output;
产量
<file>
<state>Oregon</state>
<timestamp>10:04</timestamp>
<location>Salem</location>
</file>
Borodin建议解决方案的明显必然结果是只使用哈希来初始化您的数据。 鉴于他通过将正则表达式的LHS限制为单词字符来保护您,这在功能上是相同的。 但是使用哈希可能是更好的做法,因为只有那些你想要导入到模板中的变量才是。
此外,使用此方法您将获得稍微好一点的错误消息:
use strict;
use warnings;
my $template = <<'END';
<file>
<state>$state</state>
<timestamp>$time</timestamp>
<location>$location</location>
</file>
END
my %data = (
state => 'Oregon',
time => '10:04',
location => 'Salem',
);
(my $output = $template) =~ s{\$(\w+)}{
$data{$1} // die "Variable '$1' from template not initialized"
}eg;
print $output;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.