Beefy Boxes and Bandwidth Generously Provided by pair Networks
P is for Practical

Re: inserting HTML file in a PERL script

by Tortue (Scribe)
on May 29, 2005 at 11:17 UTC ( [id://461488] : note . print w/replies, xml ) Need Help??

in reply to inserting HTML file in a PERL script

Here's the kind of thing you could do if this needs to be quick and dirty and you don't have time to learn Template::Toolkit:
my $variable = 'This is a value!'; my $variable_name = '$variable'; my $template = snarf('template.htm'); $template =~ s/\Q$variable_name\E/$variable/g; print $template; sub snarf { local $/ = undef; my $template_file = shift; open F, $template_file or die "can't open $template_file"; my $template = <F>; close F; $template; }
with the template.htm file containing:
<HTML> <HEAD> <TITLE>Title</TITLE> </HEAD> The variable is : $variable <BR><BR> <TABLE cellSpacing=0 cellPadding=0 width="100%" border=0> <TR><TD> <HR color=#99ffcc SIZE=4> <FONT face=Arial color=#99ffcc><B> Bottom text </B></FONT> </TD></TR></TABLE> </BODY> </HTML>

Replies are listed 'Best First'.
Re^2: inserting HTML file in a PERL script
by thetallblondguy (Initiate) on May 29, 2005 at 13:12 UTC

    Thank you for your help everyone, it is highly appreciated.


    About this script, it seems to be applicable only if the variable is named $variable

    Could it be possible to give me the code for a script that would replace anything starting with $xxx ?

    The variables that i have got in my html code can be named A-Z and '_' like $EMAIL or $CONTACT_ADDRESS

      yes, you could match on the $ and lookup the variable name in a hash, and replace with the value. Expects the template variables to be uppercase (A-Z and _ only) and the hash keys to be lower case.
      use strict; use warnings; my %data = ( first_name => 'Foo', email => 'Bar', ); $/ = undef; my $s = <DATA>; $s =~ s/\$([A-Z_]+)/exists $data{lc $1}?$data{lc $1}:$&/esg; print $s; __DATA__ First name is $FIRST_NAME and<br> email is: $EMAIL. junk is $JUNK
      Just to generalize the script I gave you... This replaces any variable in the template with its value in the program. It's a quick-and-dirty fix that may solve your problem if you're in a rush. Of course, as others have noted, it would be better if you used a proper templating system. Note also that this only works for simple scalar variables (e.g. $thing, $ZOWIE), not for more complicated variables such as array or hash elements (e.g., $var[$num] or $var{thing}).
      my $template = snarf('template.htm'); while ($template =~ /(\$[:alpha:]\w*)/g) { my $variable_name = $1; my $value = eval $variable_name; $template =~ s/\Q$variable_name\E/$value/g; } print $template;