akm2 has asked for the wisdom of the Perl Monks concerning the following question:

I wrote the following code to allow perl to display existing HTML files.
sub DisplayHTML() { $HTMLFileName = @_[0]; open(HTMLFNH,"<$HTMLFileName") || die "Can't open file"; print "Content-type: text/html\n\n"; while ($HTMLLine=<HTMLFNH>) { chomp $HTMLLine; print "$HTMLLine\n"; } close(HTMLFNH); } return 1;
The problem is this: As the script reads the HTML file & finds $var, I want it to print the content of $var. I don't want it to actually print "$var". Any suggestions?

Replies are listed 'Best First'.
Re: Display $var content
by chromatic (Archbishop) on Feb 27, 2001 at 01:53 UTC
Re: Display $var content
by chipmunk (Parson) on Feb 27, 2001 at 01:51 UTC
Re: Display $var content
by $code or die (Deacon) on Feb 27, 2001 at 01:52 UTC
Re: Display $var content
by dws (Chancellor) on Feb 27, 2001 at 01:58 UTC
    A side comment having nothing to do with the question you asked.
    while ($HTMLLine=<HTMLFNH>) { chomp $HTMLLine; print "$HTMLLine\n"; }
    This seems odd. Chomp removes the trailing newline, only to have it added again for the print. I suspect that there's some cargo-cult programming involved here.
    while ($HTMLLine=<HTMLFNH>) { ... whatever you need to do for interpolation print $HTMLLine; }
    should be sufficient.
      Chomp doesn't remove the trailing newline, It removes any line ending that corresponds to the current value of $/ which isn't always "\n". On DOS/WinXx machines it winds up being "\r\n" and under Mac winds up being "\r" if I remember them right. It can't hurt to let it alone as it might drop a few chars from the overall transmission and may make some wonky web clients a bit happier...

      --
      $you = new YOU;
      honk() if $you->love(perl)

        On Windows, $/ is still "\n". The "\r\n" line-endings are converted to "\n" automatically when a file is read, and "\n" is converted to "\r\n" when a file is written. (Unless binmode has been called on the filehandle.)

        On a Mac, $/ is still "\n", but "\n" means "\015" and "\r" means "\012".

        So, if $/ has not been set explicitly,

        $orig = <>; chomp($new = $orig); $new = "$new\n"; print $orig eq $new ? "yes" : "no";
        will print yes on Unix, Windows, and Mac.

        Of course, if $/ has been changed, then all bets are off. :)

Re: Display $var content
by Masem (Monsignor) on Feb 27, 2001 at 02:01 UTC
    While I know you can do this with perl, I would also say to not reinvent the wheel -- look at CPAN modules like Template Toolkit which easily support variable substituion into a predefined file, e.g.:

    .pl file

    use Template; %hash = ( name => 'my name' ); $tt = new Template; $tt->process( 'template.html', { data = \%hash } );

    template.html

    Hello, [% data.name %]! How are you today!