DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world
Simple Perl Templating
Useful when you can't install modules because your host doesn't allow it:
sub parse_template() {
my($file, %context) = @_;
my($buffer) = "";
open(FILE, $file) || die("Cannot open template " . $file);
while ($line = <FILE>) {
$line =~ s/\$(\w+)/$context{$1}/g;
$buffer .= $line;
}
return $buffer;
}
To use it, put values in the context map:
%context = (
"var1" => "value1",
"var2" => "value2",
);
$out = &parse_template("template.txt", %context);
print $out;






Comments
Snippets Manager replied on Mon, 2012/05/07 - 2:14pm
def parse_template(filename, context) text = File.readlines(filename).join text.gsub(/\$(\w+)/) { |match| context[match[1..-1]] } endSnippets Manager replied on Mon, 2012/05/07 - 2:14pm
def parse_template(filename, context) text = File.readlines(filename).join text.gsub(/\$(\w+)/) { |match| p match; context[match[1..-1]] } end context = { 'var1' => 'value1', 'var2' => 'value2' } out = parse_template('template.txt', context) print outI did leave out the error handling though.