introduction to web programming Formatting the Output Finally, we close this section with a note about formatting the outputs of your CGI applications so that your HTML is legible when "viewing the source". When reading an HTML document, a Web browser really does not care how the code is formatted. Since it ignores white space and new line characters anyway, a Web browser would be just as happy receiving one huge line of HTML code all smushed together as it would receiving a neatly formatted and human-legible HTML document. However, human readers (especially you when debugging) need to have HTML code in a format which helps you read lines and quickly analyze the output generated by your scripts.

Thus, it is very useful when printing with Perl, to use the newline character "\n". This character will introduce a newline into your output much like a <BR> does in HTML so that the text sent out by your CGI application will be formatted for easy reading.

For example, the following HTML could be displayed in two ways. First, you could type:

    print "<TABLE>";
    print "<TR>";
    print "<TD>First Name</TD>";
    print "<TD>Selena</TD>";
    print "</TR><TR>";
    print "<TD>Last Name</TD>";
    print "<TD>Sol</TD>";
    print "</TR></TABLE>";

This might seem pretty legible as Perl code, but you would receive the following HTML source code, compressed into one line:

<TABLE><TR><TD>First Name</TD><TD>
Selena</TD></TR><TR><TD>Last Name
</TD><TD>Sol</TD></TR></TABLE>

This code would be difficult to read, especially if an entire HTML page was formatted that way. On the other hand, you could use the following code:

    print "<TABLE>\n";
    print "<TR>\n";
    print "<TD>First Name</TD>\n";
    print "<TD>Selena</TD>\n";
    print "</TR>\n<TR>\n";
    print "<TD>Last Name</TD>\n";
    print "<TD>Sol</TD>\n";
    print "</TR>\n</TABLE>";

This time, when viewing the source, you would see the following HTML code neatly formatted:

<TABLE>
<TR>
<TD>First Name</TD>
<TD>Selena</TD>
</TR>
<TR>
<TD>Last Name</TD>
<TD>Sol</TD>
</TR>
</TABLE>

There are many other formatting constructs that can be included within a double-quote print or variable assignment, of course. The following table outlines several important ones.

Construct Description
\n Newline
\r Return
\t Tab
\b Backspace
\v Vertical Tab
\e Escape
\\ Backslash
\" Double Quote
\l Make next character lowercase
\L Lowercase every character until \E
\u Uppercase the next character
\U Uppercase every character until \E
\E Terminate \L or \U

It is not essential for you to keep formatting in mind, but it will make debugging much easier if it involves investigating the HTML code. Conscientious formatting is also considered good style in general.

Another benefit of using the "here document" method is that since the Perl prints out the text within the marker field exactly as you type it, you need not use the \n for newlines, because they are already incorporated.

Previous | Next | Table of Contents