๐Ÿ“˜ %Templating% engine written in Perl 6

Implement a simple templating engine, which substitutes values in placeholders of the form %name%.

The objective is to create a function that takes a template string and a hash with named values and does the substitution. So, let us prepare and pass them to a function. Notice that, in Perl 6, it is possible to pass a hash as easy as you pass a scalar (see also Task 65, Passing arrays to subroutines).

my $template =ย 'Hello, %name%! Welcome to %city%!';
my %data = (
ย ย ย ย name => 'Klara',
ย ย ย ย city => 'Karlovy Vary',

say process_template($template, %data);

Inside the function, the hash is passed as a single hash variable.

sub process_template($template is copy, %data) {
    $template ~~ s:g/ ‘%’ (\w+) ‘%’ /%data{$0}/;
    return $template;

The function modifies the value of the first argument; this is why it is marked with theย is copy trait.

The regex is global, which is turned on by theย :g regex adverb. A regex is looking for words between the two percentage symbols. In Perl 6, non-alphanumeric characters must be quoted or escaped, so bothย '%' andย \% are accepted. The second part of the replacement is using the matched value as the key for fetching the value from theย %data hash.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s