Over a million developers have joined DZone.

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 = ) {
        $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;
Topics:

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}