Home > Articles

  • Print
  • + Share This

Reading External Files with Perl

Script 1–1 is a simple script that allows you to open an ordinary text file and print it to the screen. To begin, start with this simple text file, which we will use for the next couple of examples. Name the file article1.txt and write the following lines as its contents:


Self protection How to fend off an attacker with your stiletto heel.

To open a file for reading, use the open command. Makes sense, right? Then you need to assign a FILEHANDLE to it and the name of the file you wish to open.

Script 1–1read.cgi

open(ARTICLE1, "article1.txt");
while (<ARTICLE1>) # like while($_ = <ARTICLE1>)
  print; # like print($_);
close (ARTICLE1);

When run from the command line, this script prints out the contents of article1.txt, which is what we want. First, what this does is open article1.txt and assign it the FILEHANDLE ARTICLE1. The while statement takes the ARTICLE1 FILEHANDLE so that while this file still has content, it gets printed. Then the FILEHANDLE ARTICLE1 is closed.

Once you have both article1.txt and read.cgi saved, go to a command prompt in that directory and type:

perl read.cgi

The contents of article1.txt will be output to your screen just as expected.

This is great and all, but you want to publish these .txt files as Web pages. If you try to load Script 1–1 from your browser, you'll get an error. In order to avoid an error, an HTML Content-type needs to be defined, and the appropriate HTML header and footer information needs to be set to format the HTML page.

Whenever you write a script that will output anything to the browser, you need to use a Content-type to let the script and the browser know how to communicate with each other. After you open a Content-type you can then use the print command to print HTML tags to format your output to the browser.

  • + Share This
  • 🔖 Save To Your Account

Related Resources

There are currently no related titles. Please check back later.