It can be annoying to output HTML using double quotes. You may find yourself doing things like this:
print "<img src=\"$img\" alt=\"$alttext\">\n"; print "<a href=\"$url\">A hypertext link</a>\n"; |
Escaping all those quotes with backslashes can get tedious and unreadable. Luckily, there are a couple of ways around it.
``Here'' documents allow you to print everything until a certain marker is found:
print <<"END"; <img src="$img" alt="$alttext"> <a href="$url">A hypertext link</a> END |
You can specify what end marker you want on in the print statement.
The fact that the marker is in double quotes means that the material up until the end marker is found will undergo interpolation in the same way as any double-quoted string. If you use single quotes, it'll act like a single-quoted string, and no interpolation will occur.
If you use backticks, it will execute each line via the shell.
The end marker must be on a line by itself, at the very start of the line. Note also that the print statement has a semi-colon on the end.
Another way of avoiding excessive backslashes in your code is to use the qq() or q() operators/functions.
These quotes are covered on page 41 of the Camel book.
print qq(<img src="$img" alt="$alttext">\n); print qq(<a href="$url">A hypertext link</a>\n); |
Like the matching and substitution operators m// and s///, the quoting operators can use just about any character as a delimiter:
print qq(<a href="$url">A hypertext link</a>\n); print qq!<a href="$url">A hypertext link</a>\n!; print qq[<a href="$url">A hypertext link</a>\n]; print qq#<a href="$url">A hypertext link</a>\n#; |
If the opening delimiter is a bracket type character, the closing delimiter will be the matching bracket.
Always choose a delimiter that isn't likely to be found in your quoted text. A slash, while common in non-HTML uses of the function, is not very useful for quoting anything containing HTML closing tags like </p>.
The following exercises practice using CGI to output different Perl data types (as taught in Introduction to Perl) such as arrays and hashes. You may use plain double quotes, ``here'' documents, or the quoting operators as you see fit.
Write a CGI program which creates an array then outputs the items in an unordered list (HTML's <ul> element) using a foreach loop. If you need help with HTML, there's a cheat sheet in Appendix D.
Modify your program to print out the keys and values in a hash, like this:
Name is Fred
Sex is male
Favourite colour is blue
Change your CGI program so that you output a table instead of an unordered list, with the keys in one column and the values in another. An example of how this could be done is in cgi-bin/hashtable.cgi