Create a Free Website

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.

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.

TRY This Website Builder FREE!

No Credit Card Needed!
Create beautiful,professional websites
WITHOUT Learning to Code!!

Use this Next Generation Builder
to make blogs, portfolios or
full blown websites.
No Experience Needed!

SquareSpaceSquareSpace

Start Your Website Now!SquareSpace

Professional websites
Without the HASSLE!



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

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";