- New Features
- Reading External Files with Perl
- Reading an External File through a Browser
- Project I: Automating Articles
- Project II: Writing to External Files
- Recap
- Advanced Projects
Reading an External File through a Browser
Script 12 shows you a simple way to have your script print out an external file through your browser.
Script 12 readarticle.cgi
#!/usr/bin/perl 1. print "Content-type: text/html\n\n"; 2. print "<HTML>\n<BODY BGCOLOR=\"#FFFFFF\">\n\n"; 3. open(ARTICLE1, "article1.txt"); 4. while (<ARTICLE1>) 5. { 6. print; 7. } 8. close (ARTICLE1); 9. print "</BODY>\n"; 10. print "</HTML>";
HOW THE SCRIPT WORKS
1. This line tells the browser to expect HTML during this function. If this is not included, the browser has no way of knowing that this is HTML content and things will undoubtedly get a little screwy.
2. This next line is where the script starts writing the HTML tags with the header tags. Be sure to watch out for special characters that do not print correctly (such as quotes) and precede them with a backslash (\). Follow all the remaining HTML code like this in a similar manner.
3. The script is now told to open article1.txt and assign the name ARTICLE1 as the FILEHANDLE.
47. Open the ARTICLE FILEHANDLE and loop through each line. During each iteration of the loop, the contents of the current line are stored in $_. Using print with no arguments simply prints out $_, the current line of the file.
8. Close the FILEHANDLE.
910. Now you need to close off the file with the footer HTML tags followed by the \n (line break) tags to make the format look nice and clean.
NOTE
These are simple .txt files and will not print out line breaks unless they are coded with HTML tags in the .txt file.