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

Snippets has posted 5883 posts at DZone. View Full User Profile

Simple Perl Templating

08.15.2005
| 1360 views |
  • submit to reddit
        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

Err, parse template doesn't need that debug print. Should look like this: def parse_template(filename, context) text = File.readlines(filename).join text.gsub(/\$(\w+)/) { |match| context[match[1..-1]] } end

Snippets Manager replied on Mon, 2012/05/07 - 2:14pm

In Ruby, just for kicks: 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 out I did leave out the error handling though.