Interpolating text from a file
Posted by Pat (Pat), 16 April 2004In a Perl CGI, I'm trying to generate an HTML page using some literal text and a file containing needed HTML text.
An example of the file material might be:
'The mouse ate the $x' written without interpolation so the $x appears in the file.
I open the file for input and read in the segment using code like:
open FILEHANDLE, "<msg_file.txt";
$segment = <FILEHANDLE>;
Then I make an assignment: $x = "cheese";
Finally, I write out the HTML segment with a statement like:
print "<br> $segment";
The result has $x where I had expected "cheese" to appear.
How can I do better?
Thanks in advance,
Posted by admin (Graham Ellis), 16 April 2004Hi, Pat .... good question this one. It doesn't work the way you want it to because for most (non-programmer) users, the idea of a program that changes anything starting with a $ in their data files would be pretty dis-concerting
and the results:
Explanation .... I've used regular expressions to find all simple variable names hidden in the line of text and capture the variable name to $1. I've replaced the variable name with the result of executing the code (the e switch) $$1 - $ really means "contents of", so this is the contents of the variable which is named in the captured $1 variable.
As the front of Larry Wall's "camel book" says ... "there's more than one way to do it". Perhaps other posters will follow up with their own favourite solutions!
Posted by Pat (Pat), 16 April 2004Graham,
Thanks for the reply -- and the solution.
Last night in bed I realized my problem was just a "find and replace" situation. But you've outlined the solution very nicely, and I'll use it as the base for my work.
Thanks for taking the time to decode my question and supply the "right" answer.
You mention Larry Wall. He developed Perl while he worked at the Jet Propulsion Laboratory. I worked there during his era, interfaced with him occasionally, but had no idea his product would become so popular. That was years ago, but I'm sure he's still a nice guy.
Posted by admin (Graham Ellis), 16 April 2004Pat ... you brought a smile to my face. I've had the pleasure of meeting with Larry; still very much a "nice guy" yet those words seem inadequate somehow.
P.S. Please don't quote my answer as being "the right one" - I like it, but "there's more than one way"
PH: 01144 1225 708225 • FAX: 01144 1225 899360 • EMAIL: firstname.lastname@example.org • WEB: http://www.wellho.net • SKYPE: wellho