HERE documents can also be used as templates. Since Perl will simply ignores variables that contain no data when printing HERE documents, variables can be inserted into the text as place holders. If the script that prints the HERE document assigns a value to the variables, they will be inserted into the document; otherwise the space will be left blank.
The following program is a CGI script that receives an input parameter from an HTML form and inserts it into a HERE document. If the CGI parameter contains a value, it will be printed. When the CGI parameter contains nothing, or when the script is invoked without the parameter (when it is called from the link below, for instance), no text will be printed.
#!/usr/local/bin/perl use CGI; $q = new CGI; $message = ''; $field = $q->param('text_sent'); chomp($field); # we'll add this conditional statement to show that the # script is actually working; it works just as the form # field data: if no data comes in, nothing is displayed if ($field ne '') { $message = "<p>Received form data: $field</p>\n"; } # the HERE document starts below # note that the value of the input field 'text_sent' is set to the # variable $field; this allows the HTML page to include the form field # value every time the script is invoked; # note also that the @import statement for the style sheet must be # escaped; otherwise, Perl would assume @import to be an array variable print <<END; Content-type: text/html <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>CS10100-2, Winter 2005</title> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" /> <style type="text/css" xml:space="preserve"> \@import "http://www.classes.cs.uchicago.edu/archive/2006/winter/10100-1/html/javascript/cs101.css"; </style> </head> <body> <h3>Test CGI Script</h3> <p>$message</p> <form action="http://people.cs.uchicago.edu/~wfreis/cgi_ex/perl_here_doc.pl" method="post" name="form1"> <p>Enter something:</p> <input type="text" name="text_sent" value="$field" size="50" maxlength="50"> <br /><br /> <input type="reset" name="resetButton" value="Reset" /> <input type="submit" name="submitButton" value="Submit" /> </form> <br /> </body> </html> END # Make sure that the ending token of the HERE document is # not at the very end of the file. There needs be at least # a return character following or Perl will choke on it.
Note that the incoming CGI parameter is also printed in the form input field. This technique can be used to return user data during validation. If the validation of some required form data determines that some data needs to be resubmitted, it is good policy to return all valid data with the form so that the user does not need to fill it in again. Placeholder variables in a HERE document can accomplish just that.