The following is a short subroutine that lets you implement a rudimentary template system, where a word specified in square brackets is replaced by the return value of that method call in a given object.
Caveats:
This will probably become a module in the future, with added safety features and customizability. But if you need to handroll a quick-and-dirty template (such as reading fields from a database and sending E-mails), this can get you started.
sub apply_template { my ($object, $template) = @_; $template =~ s/\[(\w+)\]/$object->$1/emg; return $template; } # Example usage: my $template = "Hello [name]. You are [age] years old!"; # We assume there is an object called "Person" with # accessor methods for "name" and "age". my $monkey = new Person (); $monkey->name("Maybelle"); $monkey->age(4); my $message = apply_template($monkey, $template); # prints "Hello Maybelle. You are 4 years old!" print $messane, "\n";
In reply to A quick and dirty template system by rrwo
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |