Printing HTML
#!/usr/bin/perl
print "Content-type: text/html\n\n";
print "<html><head>\n";
print "<title>CGI Test</title>\n";
print "</head>\n";
print "<body><a href=\"http://someplace.com\">Click Here</a>\n";
With the need to escape the quotes and add \n characters for source readability, it is a bit tedious to constantly escape quote marks and write in new line characters. An easier way to do this is to use a special print command in Perl:
print <<ENDHTML;
....your HTML code here.....
ENDHTML
This print command tells the program to print the HTML code until it finds the word ENDHTML again on its own. You can use any word or group of letters you like, just be sure you use the same thing when you want to end the HTML code. For instance, some people use EOM to do this:
print <<EOM;
....your HTML code here.....
EOM
Just remember to use the exact same thing after the << characters and after the HTML code, and it is case sensitive. Also, when you end the HTML code, you just need your word-- no semicolon. The semicolon only goes with the first print statement.
This allows you to write the code without the need to escape the quote marks, and new lines are created where you break the lines in your code. Here is an example of the last script written in this manner:
#!/usr/bin/perl
print "Content-type: text/html\n\n";
print <<ENDHTML;
<html>
<head>
<title>CGI Test</title>
</head>
<body>
<a href="http://someplace.com">Click Here</a>
</body>
</html>
ENDHTML
This is even better if you are coding a large number of links, images, and other things that need quote marks. It keeps a long page of HTML code from becoming a blur of print statements.
However, other special characters in Perl still need to be escaped. Remember the @ sign? It will still need to be escaped, as will any other special characters that set off special meanings in Perl (such as $, @, % ,*). So, if you use one of these, remember to escape it with the \ symbol, like in the example below:
#!/usr/bin/perl
print "Content-type: text/html\n\n";
print <<ENDHTML;
<html>
<head>
<title>CGI Test</title>
</head>
<body>
<a href="mailto:john\@pageresource.com">Mail Me, or Else!</a>
</body>
</html>
ENDHTML
Now that you have seen two ways to write HTML in Perl, you can decide which one you are more comfortable with. You can use a print statement for short HTML segments, and this technique for longer segments. Either way, you'll get your HTML.
Well, that's it for writing HTML, let's go on to: Perl Variables.
Copyright © 1997-2010 The Web Design Resource. All rights reserved. Disclaimer.

