in reply to Help with 'Use of uninitialized value...' error in DB code
I wanted to use variables in database 'text'(content for a website). However, since perl won't use the variables in a database, it would just show the variable (ie: $_co_name for Company Name) in the text.Ok, so it seems like what you're really after here is a home grown template system, right? Is it possible to use an existing robust one like Template Toolkit or HTML::Template? Using TT as an example, you would have the string I work for [% co_name %], the best company there is! stored in the db. Then perl code would look like:
So I had to make a way to replace those variables while it is reading them from the database into the hash that calls them.
my $template = Template->new(); my $vars = {co_name=>"Foo-Co"}; my $my_template_string = 'I work for [% co_name %], the best company t +here is!'; my $string; $template->process(\$my_template_string, $vars, \$string); # stores o +utput in $string print $string; $template->process(\$my_template_string, $vars ); # dumps output to S +TDOUT
$content =~ s/(\$[a-zA-Z0-9\{\'\}_]+)/ eval($vars{$1}) || $var +s{eval($1)} || eval($1) /ge;
They have the exact same pattern, and the first is a global replacement, which means that the second can never match (unless the first replacement value included a template string itself)... this goes for pretty much all of the replacement sets...$content =~ s/(\$[a-zA-Z0-9\{\'\}_]+)/ eval($temp_vars{$1}) /g +e; $content =~ s/(\$[a-zA-Z0-9\{\'\}_]+)/ $temp_vars{eval($1)} /g +e;
|
|---|