Home > Articles

  • Print
  • + Share This

Project I: Automating Articles

Throughout the projects in this book, we will list the files you will be using along with the permissions you will need to issue these files. For a description of how to change permissions on your files in Unix, please check out the brief tutorial on file permissions toward the end of Appendix B, "Miscellaneous Reference."

Files Used












Now let's see how to go about automating your articles with simple Perl scripts. Since you already have the header and footer information in the script, you can build your article HTML files without them. Otherwise, you will end up with duplicate header and footer tags.

Use the following three HTML files with their appropriate filenames (we will use these in the next few projects):


<TITLE>Article 1</TITLE>
<FONT SIZE="4"><B>Self protection</B></FONT><P>
<FONT SIZE="3">How to fend off an attacker with your
 stiletto heel.</FONT>


<TITLE>Article 2</TITLE>
<FONT SIZE="4"><B>Salads!!!</B></FONT><P>
<FONT SIZE="3">1001 ways to make salads.</FONT>


<TITLE>Article 3</TITLE>
<FONT SIZE="4"><B>Micro Minis are back</B></FONT><P>
<FONT SIZE="3">Just how short is too short?</FONT>


For our first project with the three HTML files you have just created, you will use the script random.cgi that will randomly display one of these files every time a user visits your Web page. Here is your first look at an array that is used to store the names of the files that will be randomly picked to be displayed. This is done by using the srand and rand functions.



An array is another type of variable, but instead of holding a single piece of data, an array can hold several. A scalar variable begins with a $, whereas an array begins with a @. (An easy way to remember an array is by the a in the @ sign.) An array sorts these different fields by indexing them in order starting with 0. Note that it does not begin with 1 as you would think it would.


name = ("Micah", "Chris", "Dan");
print "Array field 0 is: $name[0]\n";
print "Array field 1 is: $name[1]\n";
print "Array field 2 is: $name[2]\n";


Array field 0 is: Micah
Array field 1 is: Chris
Array field 2 is: Dan


The srand function initializes the random-number generator.


The rand function takes as its argument an integer and then generates a random number between 0 and the integer.

Script 1–3random.cgi

print "Content-type: text/html\n\n";
print "<HTML>\n<BODY BGCOLOR=\"#FFFFFF\">\n\n";
	1.	srand;
	2.	@articles = ("article1.html", "article2.html",       "article3.html");
	3.	$random_number = rand(@articles);
	4.	$article = $articles[$random_number];
	5.	open(FILE, $article);
	6.	while(<FILE>)
	7.	  print $_;
print "</BODY>\n";
print "</HTML>\n";


1. The srand function initializes the random-number generator.

2. Now an array called @articles is created, and the three files article1.html, article2.html, and article3.html are added to it. If you would like to use more than these three files or other filenames, you can simply add them in place of these. You can have as many files as you wish.

3. This is where the rand function comes into play. The rand function takes as its argument an integer, which then generates a random number between 0 and the integer. This way, a random index is chosen from the @articles array. The value is then assigned to the variable $random_number.

4. Next, we assign the chosen filename associated with the index that was randomly selected from the @articles array and place it in a new variable called $article.

  $article = $articles[$random_number];

5. open(FILE, $article); The file $article is now opened and assigned the FILEHANDLE FILE.

6–7. Now the script loops through all the lines of the file line by line while the FILE FILEHANDLE is open. While this is looping through the FILEHANDLE, during each iteration of the loop the current line of the FILEHANDLE is assigned to the special $_ variable (including the carriage return at the end). Simply printing out this variable is all that is needed. Through each iteration of the file, each line is printed out. This is the same thing that is done by the cat command in Unix, or the type command in MS-DOS/Windows.

Displaying Files by Time of Day

What if you want to display one of the three articles based on the time of day? For example, article1 from 12:01 a.m. to 8 a.m., article2 from 8:01 a.m. to 4 p.m., and article3 from 4:01 p.m. to midnight. This script will show you how by taking the $hour variable from a function called localtime, and then testing the variable with a series of if statements to determine which file to spit out to the browser.


if (statement)

The if statement tests whether a condition is true or not. If the statement is not true, it moves on.

elsif (statement)

Once the if statement has been executed, the elsif function is used to test if another condition is true.

else (statement)

else is used at the end of an if block statement to handle anything that wasn't in the previous conditions—kind of like a catch-all statement.

You can use the if statement with several elsif statements, but only use the else statement one time, which will be at the end of the entire block of if statements. See Table 1–2 for some examples of how to and how not to use these statements.

TABLE 1–2 Uses of the Else Statements





























The localtime function returns an array of nine elements of time in the following order:

($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) =


Array Number







Hour of the day (0–23)


Day of the month


Month (0 = January, 11 = December)


Year (with 1900 subtracted from it)


Day of the week (0 = Sunday, 6 = Saturday)


Day of the year (0–364)


A flag indicating whether it is daylight savings time

Script 1–4readme.cgi

print "Content-type: text/html\n\n";
	1.	($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime(time);
	2.	if(($hour >= 0) && ($hour < 9))
  $article = "article1.html";
	3.	elsif(($hour > 8) && ($hour < 16))
  $article = "article2.html ";
	4.	else
  $article = "article3.html ";
	5.	open(FILE, $article);
	6.	while(<FILE>)
	7.	  print $_;
close (FILE);


1. The localtime function returns an array of nine elements and assigns these values to their associated variables, $sec, $min, $hour, $mday, $mon, $year, $wday, $yday, $isdst.

2–7. These next several lines use the if, elsif, and else functions to check to see if these variables meet certain criteria:

if(($hour >= 0) && ($hour < 9)): First, the script looks to see if the $hour variable is between the hours of midnight (0) and 8 a.m. (8) by seeing if it is equal to or greater than 0 and less than 9. && is the logical operator used for "and." If this is true, then the variable $article is assigned the value article1.html. If not, then the script moves on to the next statement.

elsif(($hour > 8) && ($hour < 16)): Now the script checks to see if the $hour variable is between 8 a.m. and 4 p.m. If this is true, then the variable $article is assigned the value article2.html. If not, then the script moves on to the next statement.

else: Finally, if none of the previous tests were true, then a final test is done, which is just an else (in this case it is a catch-all), and $article is assigned the value article3.html.

  • + Share This
  • 🔖 Save To Your Account

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information

To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.


Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.


If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information

Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.


This site is not directed to children under the age of 13.


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information

If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information

Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents

California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure

Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact

Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice

We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020