PERL CGI Tutorial
for Writing Interactive Form Scripts

Open a File and Display its Contents.

To open a file and display its contents we use code that is very similar to the code that we used to write the file.

open (INFO,"filename.txt");

close(INFO);

Now let's create a CGI script to open the file names.txt and display it's contents in the browser. We'll leave it in its present form and in the next lesson will makes some modifications to make the data usable.

display_file.pl

#!/usr/bin/perl
print "Content-type:text/html\n\n";

print "<html>\n";
print "<head><title></title></head>\n";
print "<body>\n";

open(INFO, "names.txt");
@array=<INFO>;
close (INFO);
foreach $line (@array){
print "$line<br>\n";
}


print "</body>\n";
print "</html>\n";

Try the Script


Notice how we divided the HTML page into three sections. We modified the original CGI script for sending an HTML page to the browser.

We placed the code for opening the file and dumping the contents between the first and third sections, and added a loop(green) and another print statement to print the lines of the file.

The line @array=<INFO>;
dumps the lines of the file into an array or list that is easier to manipulate.

Saving to a file Using the Split Function
CGI Online is a service provided by Net Success 2000 Plus Inc.
PO Box 1508
Somerset, KY 42502
Last Modified: January 20, 2008

| HTML TOC | Website Design Workshop | Home |