Perl 根据模板生成文件

Perl generate a file based on a template

我正在处理一个需要我根据模板生成 .hpp 文件的用例。所以像

#ifdef changethis_hpp
#define changethis_hpp

#include<fixedheader1>
...
#include<fixedheaderN>

class changethis
{
....
};

需要根据changethis字符串的要求生成。 我怎样才能在 perl 中实现这一点?

WHITSF 我写了一个固定的 template.txt 文件,然后用 changethis 字符串替换文本,然后将其转储为 changethis.hpp。

但是有没有其他方法可以在 perl 中实现这一点?

我使用 Text::Template 完成此类任务。

有一个 Perl 常见问题解答,How can I expand variables in text strings?。它是这样开始的:

If you can avoid it, don't, or if you can use a templating system, such as Text::Template or Template Toolkit, do that instead. You might even be able to get the job done with sprintf or printf:

my $string = sprintf 'Say hello to %s and %s', $foo, $bar;

However, for the one-off simple case where I don't want to pull out a full templating system, I'll use a string that has two Perl scalar variables in it. In this example, I want to expand $foo and $bar to their variable's values:

my $foo = 'Fred';
my $bar = 'Barney';
$string = 'Say hello to $foo and $bar';

One way I can do this involves the substitution operator and a double /e flag. The first /e evaluates </code> on the replacement side and turns it into <code>$foo. The second /e starts with $foo and replaces it with its value. $foo, then, turns into 'Fred', and that's finally what's left in the string:

$string =~ s/($\w+)//eeg; # 'Say hello to Fred and Barney'

The /e will also silently ignore violations of strict, replacing undefined variable names with the empty string. Since I'm using the /e flag (twice even!), I have all of the same security problems I have with eval in its string form. If there's something odd in $foo , perhaps something like @{[ system "rm -rf /" ]}, then I could get myself in trouble.

我强烈建议您忽略大部分建议,直接进入模板系统(如第一行中所推荐)。