Step B. Use perl to open a file and display its contents on the internet

Here is our Perl textbook for reference, but it goes deeper than we need, so just read up to the first creating filters example: https://docs.google.com/viewer?url=http%3A%2F%2Fblob.perl.org%2Fbooks%2Fbeginning-perl%2F3145_Chap06.pdf

Fact to know: Create a handle to the file using the file open command:

my $filename = "somefile.txt";
open(my $fh, '<', $filename);

possible result is false so you can exit when a file is not found using or die command (with the $! being the last error message) :

open(my $fh, '<', $filename) or die "Could not open file '$filename' $!";

Fact to know: When accessing a file from the browser, the full path must be used.

my $filename = "/home/pe16132/public_html/somefile.txt";

Fact to know: loop through the file using a while loop that will stop at the end of the file:

example that prints each line in the file

while (my $line = <$fh>) {
chomp $line;
print "$line\n";
}

Fact to know: In HTML, \n does nothing, but <br/> will skip to a new line.

Fact you need to know: On our system, it is helpful to use these first 2 lines as the first lines in your perl CGI program and name your script with .pl extension:

Fact you need to know: Our panther server only allowsyour files in public_html to be accessed on the internet. Create the public_html folder using goweb. Your website URL will display when you first log on.

Your job: Create a perl script that prints the html container, and inside the body, print the contents of your file. When you access this script on the website, it should display the contents of the file.

1. Create a file to be read using vi. Put your file into public_html.

2. Create a perl script ending in the .pl extension. Make it read the file using file open command and the while loop described above. Test this on panther using perl scriptname.

3. Add the lines that our system wants as the first lines of a perl CGI script:

4. Add the html <HEAD><BODY> Open tags before the file prints. Just print this line.

5. Add the html </BODY></HEAD> close tags after the file prints.

6. Change your line print statements to also print a <BR/> to make line returns.

Test this on panther and see it print with the tags.

Test this on your website to see it print without the tags. Be sure your filename has a full path beginning with /home or it will give you an error.

You now know how to read a file on the browser.