# Nick Thornton wrote: # # So I'm writing a program to create pages from a database. In the past when # writing scripts like this I had the formatting for the pages built into the # program, this time I'm having the formatting in a separate template file. Now # the problem is how to replace strings like $variable in the template with the # value of the variable itself. Since I don't want to do a search-and-replace for # every possible variable, is there a simpler way to do this? (In the past I've # used <<HERE to interpolate when I set the variable, but I'd rather not have to # read through the template file more than once) =~wren
### To output dynamically from a template file after putting in ### what your database or your clock has to offer, ### you can do something like this: ### Some variables: $MyColour = "aabbcc"; ### should be a soft light blue $today = (localtime)[3] . "." . ((localtime)[4]+1) . "." . ((localtime)[5]+1900); $to_whom = "Folks"; $MyText = "Mytown, $today<br><br>\n\n" . "Hi $to_whom!<br>\n" . "This is the power of 'dynamic text'."; ### read template: $MyTemplate = join "", <DATA>; ### Now you might have to defuse single and double quotes: $MyTemplate =~ s,(['"]),\\$1,g; ### output: print "\n-------- not yet interpolated: ------\n"; print $MyTemplate; print "\n\n------- interpolated: --------\n"; print eval "\"$MyTemplate\""; print "\n---------------------------------------\n\n"; __DATA__ <HTML> <HEAD><HEAD> <BODY bgcolor=#"$MyColour"> $MyText </BODY></HTML>