Beefy Boxes and Bandwidth Generously Provided by pair Networks
Just another Perl shrine
 
PerlMonks  

Re: Invoke the Perl string interpolation engine on a string contained in a scalar variable.

by localshop (Monk)
on Jan 19, 2019 at 20:15 UTC ( [id://1228753]=note: print w/replies, xml ) Need Help??


in reply to Invoke the Perl string interpolation engine on a string contained in a scalar variable.

Back in the days when everybody was building their own template interpolation code I used this little snippet This code interpolates the values from a vars hashref into the text string. I suspect that it can be improved but it worked for me for a long time - any suggestions welcome.
my $text = 'this is my text with a <%VAR%> to interpolate'; my $vars = { 'VAR' => 'value taken from a data structure' }; $_ = $text; while ( /<%(.+?)%>/g) { #print "$1\n"; if (!defined $vars->{$1} ) { $vars->{$1} = 'undefined'; $vars->{MESSAGE} .= "$1 undefined <br />\n"; ## keep a log of mi +ssing variables } } $text =~ s/<%(.+?)%>/$vars->{$1}/g || warn("unable to substitute $1" +); print qq{$text\n};

Replies are listed 'Best First'.
Re^2: Invoke the Perl string interpolation engine on a string contained in a scalar variable.
by AnomalousMonk (Archbishop) on Jan 19, 2019 at 23:17 UTC
    $text =~ s/<%(.+?)%>/$vars->{$1}/g || warn("unable to substitute $1");

    This statement is puzzling. If zero substitutions are done, two warnings are emitted (assuming you have warnings enabled). What is the purpose of printing  $1 when it is undefined?


    Give a man a fish:  <%-{-{-{-<

      Thanks - yes the || warning was a hangover from first attempt that should have been removed. Here's a slightly better reworked version - NB you could probably make this more succinct using a map instead of the while.

      use strict; use warnings; use Data::Dumper; =pod Interpolates source text tags with <%keyname%> syntax with values from + hashref $vars =cut my $text = 'this is my text with a <%VAR%> to ' . 'interpolate and an no specified "<%VAR3%>"'; my $vars = { 'VAR' => 'value taken from a data structure', 'VAR1' => 'Variable 1' }; ## Identify any tags not defined within $vars and append to message while ($text =~ /<%(.+?)%>/g ) { if (!defined $vars->{$1} ) { #$vars->{$1} = " no value specified for variable $1"; #$vars->{$1} = "$1"; $vars->{$1} = ''; ## keep a log of missing variables $vars->{MESSAGE} .= "$1 undefined <br />\n"; } } $text =~ s/<%(.+?)%>/$vars->{$1}/g; print qq{\n\n\n\n$text\n}; print Dumper $vars;

        This is the way I would tend to approach this type of problem. See haukex's article Building Regex Alternations Dynamically (a technique I seem to have posted about quite often recently).

        c:\@Work\Perl\monks>perl -wMstrict -le "my $text = 'text with a <%VAR%> and <%FOO%> to interpolate <%OOPS%>'; print qq{'$text'}; ;; my $vars = { 'VAR' => 'Value Taken From A Data Structure', 'FOO' => 'Another One', }; ;; my $rx_pre = qr{ <% }xms; my $rx_post = qr{ %> }xms; ;; my ($rx_var) = map qr{ $_ }xms, join '|', map quotemeta, reverse sort keys %$vars ; print 'regex: ', $rx_var; ;; $text =~ s{ $rx_pre ($rx_var) $rx_post }{$vars->{$1}}xmsg; print qq{'$text'}; ;; log_unknown(\$text, $1, $-[1]) while $text =~ m{ ($rx_pre .*? $rx_pos +t) }xmsg; ;; ;; sub log_unknown { my ($sr_text, $unknown_tag, $offset) = @_; ;; print qq{unable to interpolate '$unknown_tag' at offset $offset} } " 'text with a <%VAR%> and <%FOO%> to interpolate <%OOPS%>' regex: (?msx-i: VAR|FOO ) 'text with a Value Taken From A Data Structure and Another One to inte +rpolate <%OOPS%>' unable to interpolate '<%OOPS%>' at offset 77
        One might also define a regex to match the acceptable pattern of any key (interpolation tag) in the  $vars hash, then use it both to check those keys when building the  $rx_var regex and then later in place of  .*? to look for unknown/failed interpolations.


        Give a man a fish:  <%-{-{-{-<

      Thanks - yes the || warning was a hangover from first attempt that should have been removed. Here's a slightly better reworked version - NB you could probably make this more succinct using a map instead of the while.

      use strict; use warnings; use Data::Dumper; =pod Interpolates source text tags with <%keyname%> syntax with values from + hashref $vars =cut my $text = 'this is my text with a <%VAR%> to ' . 'interpolate and an no specified "<%VAR3%>"'; my $vars = { 'VAR' => 'value taken from a data structure', 'VAR1' => 'Variable 1' }; ## Identify any tags not defined within $vars and append to message while ($text =~ /<%(.+?)%>/g ) { if (!defined $vars->{$1} ) { #$vars->{$1} = " no value specified for variable $1"; #$vars->{$1} = "$1"; $vars->{$1} = ''; ## keep a log of missing variables $vars->{MESSAGE} .= "$1 undefined <br />\n"; } } $text =~ s/<%(.+?)%>/$vars->{$1}/g; print qq{\n\n\n\n$text\n}; print Dumper $vars;

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://1228753]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others admiring the Monastery: (7)
As of 2024-03-28 09:50 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found