code2html.pl

#!/usr/bin/perl
#
# code2html.pl
# ============
# (c) Copyright Paul Griffiths 2007
#
# CGI script accepting an uploaded text file and
# outputting a valid XHTML 1.1 file containing the
# contents. <, >, & and " characters are replaced with
# their relevant HTML character entity references.

use CGI;

$templatefile      = "template.html";
$query             = new CGI;
$filename          = $query->param("upfile");
$filename          =~ s/.*[\/\\](.*)/$1/;
$upload_filehandle = $query->upload("upfile");

$mainmatter = "<pre>";

while ($line = <$upload_filehandle>) {
  $line =~ s/&/&amp;/g;
  $line =~ s/"/&quot;/g;
  $line =~ s/</&lt;/g;
  $line =~ s/>/&gt;/g;
  $mainmatter .= "$line";
}

$mainmatter .= "</pre>";

&printHTMLOutputFromTemplate($templatefile, $filename, $filename, $mainmatter);


# printHTMLOutput subroutine
#
# Parameters:
#   $_[0] - name of template file
#   $_[1] - title of document (replaces the string <??TITLE??> in the template file
#   $_[2] - main heading of document (replaces the string <??HEADING??> in the template file
#   $_[3] - main matter of document (replaces the string <??MAINMATTER??> in the template file

sub printHTMLOutputFromTemplate {
  die "Not enough parameters specified!\n" unless @_ == 4;
  local($templatefile, $title, $heading, $mainmatter) = @_;  
  open(TEMPLATEFILE, $templatefile) or die "Can't open $templatefile!\n";
  print "Content-Type: text/html\n\n";

  # loop until we reach <??MAINMATTER??> or until end of file

  while ( $templateline = <TEMPLATEFILE> and not $templateline =~ /<\?\?MAINMATTER\?\?>/ ) {
    $templateline =~ s/<\?\?TITLE\?\?>/$title/g;
    $templateline =~ s/<\?\?HEADING\?\?>/$heading/g;
    print "$templateline";
  }
  
  # print main matter and rest of template unless at end of file

  if ( $templateline ) {
    print "$mainmatter";

    while ( $templateline = <TEMPLATEFILE> ) {
      print "$templateline";
    }
  }
  
  close(TEMPLATEFILE);
}