regex - A tiny template language -
i pass string "partial" sql statement like:
"select %fields% ... %order% %limit%"
then want replace %fields%
either real list of fields (which array) or count(*)
. likewise replace %order%
either order ...
(which generate) or empty string , %limit%
either limit ...
(which generate) or empty string.
i want way prevent these sequences replaced. example may "turn off" replacing if percents doubled: %%fields%%
should not replaced list of fields replaced literal %fields%
.
note not insist namely on syntax. instead of percent signs may use other escape syntax (for example ${fields}
or {{fields}}
).
i want easy , (what more important) efficient way this.
note use perl.
maybe, should not invent own template language regexps , use perl module template::tiny
? efficient?
#!/usr/bin/perl use strict; use warnings; sub myreplace { ($tmpl, $hash) = @_; %hash2; foreach $key (keys %$hash) { $hash2{"%$key%"} = $hash->{$key}; $hash2{"\\%$key%"} = "%$key%"; # escaped } $re_str = "(" . (join '|', map { "\q$_\e" } keys %hash2) . ")"; $tmpl =~ s/$re_str/$hash2{$1}/g; return $tmpl; } print myreplace('select %fields% ... %order% %limit%', {fields=>'a, b, c', order=>'order id', limit=>''}), "\n"; print myreplace('select \\%fields% ... %order% \\\\%limit%', {fields=>'a, b, c', order=>'order id', limit=>''}), "\n";
Comments
Post a Comment