Online Learning Applications for Technical English


Home
Syllabus
Assignments

Instructor



Producing Homepages

Example 2: Write a Perl CGI program to read the contents of a file and print the results in a homepage.

Imagine that we have a data file with the following contents:

Filename: attendance.dat
Name, 10/2, 10/9, 10/16, 10/23, 10/30
Aki, 1, 1, 1, 1, 1
Ben, 1, 0, 0, 1, 1
Cathy, 0, 1, 1, 1, 1

Let us write a program to read the contents of this file one line at a time and display the data in a table. We need to do the following:

  • Step 1: Open the data file and read the contents into an array.
  • Step 2: Print contents in a homepage table.

Prepare a file as follows:

Filename: disp_attendance.cgi
#!/usr/bin/perl

#------------------------------
# [10/30/2002] - File created.
#------------------------------

#-----------
# Variables
#-----------
$DATA_FILENAME = 'attendance.dat';

#--------------------------------------------
# Step 1:  Open data file and read contents
#   into an array.
#--------------------------------------------
  open( DATA_FILE, "< $DATA_FILENAME" )
    or die "Cannot open data file $DATA_FILENAME: $!";
  chomp( @lines = <DATA_FILE> );
  close( DATA_FILE );

#--------------------------------------------
# Step 2:  Print HTML contents 
#--------------------------------------------
# Print header.
  print "Content-type:  text/html\n\n";

# Print HTML.
  print <<END;
<HTML>
<HEAD>
</HEAD>
<BODY>
<TABLE BORDER=1>
END

#-----
# Step 2-1:  Separate items of each line and put
#   into table rows.
#-----
  foreach $line (@lines)
  {
# Start new row.
    print "<TR>\n";

# Separate line items at the commas and put 
# into an array.
    @line_items = split(/,/, $line);

# Print each line item into the row.
    foreach $item (@line_items)
    {
      print "<TD>$item</TD>\n";
    }

# End row.
    print "</TR>\n";
  }

# End the table and homepage.
  print <<END;
</TABLE>
</BODY>
</HTML>
END

  exit;

Do some processing
AND
Print a homepage


[ View result ]

[ Back ]