Skip to content

Instantly share code, notes, and snippets.

@jef-sure
Created July 19, 2018 18:32
Show Gist options
  • Select an option

  • Save jef-sure/89faa4b35b0e8d769cc0771d647bc18a to your computer and use it in GitHub Desktop.

Select an option

Save jef-sure/89faa4b35b0e8d769cc0771d647bc18a to your computer and use it in GitHub Desktop.
use v5.10;
use strict;
use warnings;
use Data::Dumper;
sub _quote_var {
my $s = $_[0];
my $d = Data::Dumper->new([$s]);
$d->Terse(1);
my $qs = $d->Dump;
substr($qs, -1, 1, '') if substr($qs, -1, 1) eq "\n";
return $qs;
}
my $tmpl = 'The {{ PLANET }} is shining and {{ WHO }} glad to kill them all\'s at once, "yeah"';
sub translate_tmpl {
my $tmpl = $_[0];
my $bodysub = '';
my $lastidx;
while ($tmpl =~ m|(.*?)\{\{\s*(\w+)\s*\}\}|g) {
$lastidx = $+[0];
my $var = lc $2;
$bodysub .= "." if $bodysub;
$bodysub .= _quote_var($1) . qq|.(\$_[0]->{'$var'}//'')|;
}
my $left = substr($tmpl, $lastidx);
if ($left) {
$bodysub .= "." if $bodysub;
$bodysub .= _quote_var($left);
}
return "sub { $bodysub }";
}
say translate_tmpl($tmpl);
my $cfunc = eval translate_tmpl($tmpl);
say $cfunc->({
planet => 'sun',
who => 'children',
}
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment