+ All Categories
Home > Documents > Study Guide Programming in CGI/Perl · instructions to students 1 lesson assignments 7 lesson 1:...

Study Guide Programming in CGI/Perl · instructions to students 1 lesson assignments 7 lesson 1:...

Date post: 06-Sep-2018
Category:
Upload: duongnga
View: 222 times
Download: 0 times
Share this document with a friend
81
Study Guide Programming in CGI/Perl By Frankey Goss
Transcript

Study Guide

Programming in CGI/PerlBy

Frankey Goss

About the Author

Frankey Goss is a graduate of the University of Tennessee with aBachelor of Arts degree in Sociology and a Masters of Sciencedegree in Information Sciences. Currently she is pursuing herMasters of Science degree in Education Instructional Technology,Curriculum, and Evaluation.

Ms. Goss works for a variety of educational and corporate institu-tions where she serves as Webmaster, Web designer, graphicdesigner, server administrator, technical writer, instructionaldesigner, online instructor, and Web development professional.

All terms mentioned in this text that are known to be trademarks or servicemarks have been appropriately capitalized. Use of a term in this text should notbe regarded as affecting the validity of any trademark or service mark.

Copyright © 2005 by Penn Foster, Inc.

All rights reserved. No part of the material protected by this copyright may bereproduced or utilized in any form or by any means, electronic or mechanical,including photocopying, recording, or by any information storage and retrieval system, without permission in writing from the copyright owner.

Requests for permission to make copies of any part of the work should be mailed to Copyright Permissions, Penn Foster, 925 Oak Street, Scranton,Pennsylvania 18515.

Printed in the United States of America

INSTRUCTIONS TO STUDENTS 1

LESSON ASSIGNMENTS 7

LESSON 1: CREATING YOUR FIRST CGI/PERL FORM 9

GRADED PROJECT—LESSON 1 21

LESSON 2: ARRAYS AND DATA FILES 25

EXAMINATION—LESSON 2 33

LESSON 3: SELECTION STRUCTURE AND FUNCTIONS 37

EXAMINATION—LESSON 3 45

LESSON 4: STRING MANIPULATION AND DBM DATABASES 49

EXAMINATION—LESSON 4 59

LESSON 5: E-MAIL, COOKIES,AND REDIRECTION 63

GRADED PROJECT—LESSON 5 71

SELF-CHECK ANSWERS 75

iii

Co

nt

en

ts

Co

nt

en

ts

1

Instru

ctio

ns

Instru

ctio

ns

YOUR COURSE

Welcome to the world of CGI and Perl. Perl is a stable, cross-platform programming language that was created by LarryWall in the late 1980s as a way of bringing together the functions of many popular Unix text-processing applications,such as sh, sed, and awk. It’s supported on over 94 operat-ing systems, including Unix, Macintosh, Windows, and Linux.Perl’s power lies in its ability to work seamlessly with third-party databases, including Oracle, Sybase, Postgres, MySQL,and others. It also works with HTML, XML, and other markuplanguages and supports Unicode. Since 1987, Perl has beenopen-source software, licensed under its Artistic License orthe GNU General Public License.

With the arrival of the World Wide Web, Perl achieved evengreater fame as a convenient way to write Common GatewayInterface (CGI) scripts for dynamic Web pages. CGI defined astandard way of connecting a Web server to a script runningon a server. When a server receives a request for a CGIscript, it executes the script, handing over the requestedinformation to the script. The script then runs and generatesthe appropriate output. That output is dutifully sent back tothe browser by the Web server. Most CGI scripts are writtenin Perl, which is the most popular Web programming lan-guage because of its text manipulation capabilities, rapiddevelopment cycle, and data encryption features.

This study guide is intended to help you achieve the objec-tives of this course. Each assignment in the study guide contains summaries and insights regarding the requiredreading in your textbook, as well as suggested exercises and problems so you can test yourself on what you’ve readand studied.

Think of this study guide as a roadmap for your CGI/Perlstudy. You should read the study guide carefully in conjunc-tion with the textbook. The reading assignments in the studyguide are the chapters in the textbook. To work through thecourse material, follow the instructions in the “Study Plan”section of this study guide.

Instructions to Students 2

OBJECTIVES

When you complete this study guide, you’ll be able to

■ Create online forms using Perl

■ Create CGI scripts using Perl

■ Use Perl on a Unix server

■ Use Perl with DBM databases

■ Write cookies

■ Manipulate and process data via the Internet and Web servers using Perl

YOUR TEXTBOOK

Your textbook for this course is CGI/Perl by Diane Zak. This book contains the material on which you’ll be testedduring this course. You read should read it carefully andthoroughly.

Your textbook contains several useful features that will behelpful as you work through this course, including

■ A table of contents that shows a breakdown of the topicscovered by the text

■ A preface that offers a description of the informationpresented in the text

■ Tables, screen captures, and drawings that illustrateimportant topics

■ An index that enables you to quickly locate informationin the text

Take a moment to read the “Read This Before You Begin”section on pages xiv–xviii of your textbook. Because you’ll be using Windows to create and run your Perl scripts ratherthan a Unix server, you’ll need to complete all of the stepspresented on those pages to set up your system to accommo-date your programming tasks.

To complete all of the steps and projects in this textbook,you should

■ Follow the instructions on page xiv to obtain the datafiles from your instructor or from www.course.com

■ Follow the instructions on page xiv to download theActivePerl interpreter from www.activestate.com (Figures 1 and 2)

Instructions to Students 3

FIGURE 1—ActiveState Homepage

Instructions to Students

■ Follow the steps on page xv to download and install the Mail::Sendmail module from www.perl.com/CPAN-local/authors/id/M/MI/MIVKOVIC/. Detailedinstallation instructions are available at the http://theoryx5.uwinnipeg.ca/CPAN/perl/pod/perlmodinstall.html Web site.

■ If you’re using Windows 2000 Professional, follow theinstructions on pages xv–xvii to install and configureInternet Information Server 5.0 so you can test yourscripts on your desktop.

A list of common Unix commands is provided in Appendix A(page 349). You won’t use Telnet commands in this course,but these commands are essential if you’re given Telnetaccess to a Unix server. Appendices B (page 351) and C (page 355) in your textbook offer a brief introduction to Unix-based editors that you can use to make changes to CGIscripts directly on the Unix server. Again, you won’t use

4

FIGURE 2—ActivePerl Interpreter

Instructions to Students

these programs in this course, but they’re commonly used byPerl programmers. Appendix D (page 359) offers a summaryof ASCII codes. Knowledge of these codes is useful but notessential to your course of study.

COURSE MATERIALS

This course includes the following materials:

1. Your course textbook, CGI/Perl, which contains theassignment reading material

2. This study guide, which contains an introduction toyour course, plus

■ A lesson assignments page with a schedule of study assignments

■ Assignment introductions that emphasize the mainpoints in the textbook

■ Self-checks to help you assess your understandingof the material

■ A graded project or examination for each of the lessons in this course

■ Answers to the self-checks

A STUDY PLAN

This study guide divides the course material into five lessons. Each lesson is divided into multiple assignments.Each assignment includes a reading from your textbook and a supplementary assignment in this study guide. Self-check questions appear at the end of each assignment soyou can check your understanding of what you’ve learned.Be sure to complete all of the work in each lesson beforemoving on to the next. You’ll find this easy to do if you follow the plan of study outlined below.

1. Note the pages for each assignment and read the summary material in this study guide.

2. Quickly read the assigned pages in your textbook.

5

3. Go back and slowly read the assigned pages in yourtextbook again. Pay careful attention to what you’rereading. Keep in mind the learning objectives and howthe material relates to them. Pay particular attention todefinitions and main concepts.

4. Answer the questions and problems provided in the self-checks in this study guide. The self-checks are anintegral part of the assignment. Don’t move on to thenext assignment without taking the self-check. Thesequestions are for your use only—they aren’t graded.Don’t send your answers to the school.

5. Once you’ve completed the assignment self-check, turnto the answers provided at the back of this study guide.The self-checks are designed to test how well you under-stand the material, so test yourself honestly. Make everyeffort to complete the questions before turning to theanswers at the back of this study guide. If you find anyweak areas in your knowledge, go back and review therelevant material until you understand it.

6. Follow this procedure for each assignment until you’vecompleted the lesson.

7. When you’re confident that you understand all theassigned material within a lesson, complete the gradedproject or examination for that lesson. Submit yourgraded project or examination using one of the optionsdescribed in your first shipment.

8. If you have any questions during your studies, e-mailyour instructor for assistance.

You’re now ready to begin your study of CGI/Perl. Good luck!

Instructions to Students 6

Lesson 1: Creating Your First CGI/Perl Form

For: Read in the Read in study guide: the textbook:

Assignment 1 Pages 9–14 Pages 1–16

Assignment 2 Pages 14–16 Pages 21–37

Assignment 3 Pages 17–20 Pages 43–69

Graded Project 40272900 Material in Lesson 1

Lesson 2: Arrays and Data Files

For: Read in the Read in study guide: the textbook:

Assignment 4 Pages 25–28 Pages 79–101

Assignment 5 Pages 28–32 Pages 111–137

Examination 40273000 Material in Lesson 2

Lesson 3: Selection Structure and Functions

For: Read in the Read in study guide: the textbook:

Assignment 6 Pages 37–40 Pages 147–172

Assignment 7 Pages 40–43 Pages 181–206

Examination 40273100 Material in Lesson 3

Lesson 4: String Manipulation and DBM Databases

For: Read in the Read in study guide: the textbook:

Assignment 8 Pages 49–53 Pages 215–243

Assignment 9 Pages 53–57 Pages 255–278

Examination 40273200 Material in Lesson 4

7

Assig

nm

en

tsA

ssign

me

nts

Lesson 5: E-mail, Cookies, and Redirection

For: Read in the Read in study guide: the textbook:

Assignment 10 Pages 63–65 Pages 287–302

Assignment 11 Pages 66–68 Pages 311–325

Assignment 12 Pages 69–70 Pages 333–341

Graded Project 40273300 Material in Lesson 5

Lesson Assignments8

9

Le

ss

on

1

L

es

so

n

1

Creating Your First CGI/Perl FormThis lesson consists of three assignments that correspond toChapters 1, 2, and 3 in your textbook.

OBJECTIVES

When you complete this lesson, you’ll be able to

■ Use basic Internet terminology

■ Create a basic CGI script using the Perl programming language

■ Run a CGI script from the command line and a Web browser

■ Create a hyperlink to a CGI script

■ Use the CGI.pm module to parse data

■ Plan and create a CGI script that processes form data

■ Declare scalar variables in a CGI script

ASSIGNMENT 1: AN INTRODUCTION TO CGI AND PERLRead this introduction and the learning objectives on page 1 of CGI/Perl. Then read Chapter 1, pages 1–16, in the textbook.When you’ve completed the material, take the self-check thatappears at the end of Assignment 1.

This assignment provides an introduction to Internet termi-nology, CGI scripting, and the Perl programming language. Inthis assignment, you’ll create, test, and run your first CGIscript written in Perl. Since the introduction of Perl in thelate 1980s, Perl has become the most common programminglanguage used with CGI scripting.

Programming in CGI/Perl10

Terminology

Carefully read the material on Internet terminology, staticand dynamic Web pages, and CGI on pages 2–6 of your textbook.

You should be familiar with the terms that are used whendiscussing the Internet, dynamic and static Web pages, CGI,and Perl. Understanding these terms will help you as youwork through your CGI/Perl course.

■ ActivePerl. A software package designed and distributedby ActiveState that’s used for developing Perl onWindows platforms.

■ Array. A variable that can hold multiple scalar valuesthat are accessible by their position (index) in the array.Not a list.

■ ASCII (American Standard Code for InformationInterchange). This is the de facto worldwide standardset of numbers that’s used to represent all upper- andlowercase Latin letters, numbers, punctuation marks,and other symbols. There are 128 standard ASCII codes,each of which can be represented by a seven-digit binarynumber: 0000000 through 1111111, plus parity.

■ Binary operator. An operator that has operands on both sides.

■ Boolean. A variable that has a value of “true” or “false.”A scalar value is false if the variable is empty, zero, orundefined. The same value can be true if the variable is nonempty.

■ Browser. Client software that’s used to look at Internetresources. Examples include Microsoft’s InternetExplorer and Netscape’s Navigator.

■ CGI (Common Gateway Interface). A set of rules thatdescribe how a Web server communicates with anotherpiece of software on the same machine and how theother piece of software (i.e., the CGI program) talks tothe Web server. Any piece of software can be a CGI

Lesson 1 11

program if it handles input and output according to theCGI standard. A CGI script can be written in a variety ofprogramming languages, but Perl is most commonly used.

■ cgi-bin. The most common name of the directory on aWeb server in which CGI programs are stored. The “bin”part of cgi-bin is a shorthand version of “binary.” Althoughmost programs that use CGI are stored in this directory,it isn’t a requirement for using CGI.

■ Client. A software program that’s used to contact andobtain data from a server software program on anothercomputer, often across a great distance. Each client pro-gram is designed to work with one or more specific kindsof server programs, and each server requires a specifickind of client. A Web browser and an FTP program arespecific kinds of clients.

■ Cookie. A piece of information sent by a Web server to aWeb browser. The browser software is expected to savethe information and send it back to the server wheneverthe browser makes additional requests from the server.Depending on the type of cookie used and the browser’ssettings, the browser may or may not accept the cookie.The server may save the cookie for either a short or longperiod of time.

■ CPAN (Comprehensive Perl Archive Network). A collec-tion of Perl modules available for free on more than onehundred mirror sites worldwide.

■ Dynamic Web pages. Web pages that are capable ofaction and/or change.

■ Element. An item in an array, hash, or list.

■ Environment variables. Variables created and set bythe server that runs the script. CGI programming usesenvironment variables to gather information about thecomputer/browser that the script viewer is using.

■ GET request. One of the methods a browser uses torequest information from a Web server. In most cases,GET requests are for documents. The POST request isused to send data from form input fields.

Programming in CGI/Perl12

■ HTML (HyperText Markup Language). The languageused to create hypertext documents for use on the World Wide Web. HTML files are meant to be viewedusing a World Wide Web client program, such asNetscape or Mosaic.

■ HTTP (HyperText Transfer Protocol). The underlyingprotocol used by the World Wide Web. HTTP defines how messages are formatted and transmitted and what actions Web servers and browsers should take in response to various commands.

■ IP address. A 32-bit number that identifies the senderor receiver of information sent in packets across theInternet.

■ Modules. A collection of prewritten code stored in a file.

■ perl. If perl is written in all lowercase letters, it refers tothe actual interpreter or program that runs from thecommand line.

■ Perl. Perl written with an uppercase P refers to the programming language.

■ Static Web pages. Web pages that are fixed; that is,they must be changed manually.

■ Syntax. Programming language rules that control which words the computer understands, which combi-nations of words are meaningful, and what punctuationis necessary.

■ Unicode. A 16-bit coding scheme for characters that’ssupported by Perl.

■ UNIX. An operating system invented by Ken Thompsonin 1969. Perl programmers commonly use UNIX serversto create Perl/CGI scripts and programs.

■ URL (Uniform Resource Locator). A URL is the addressof a specific Web site or file on the Internet. A URL can’thave spaces or certain other characters and uses forwardslashes to denote different directories.

Lesson 1 13

■ Variable. A way to store and refer to a block of memory.Perl’s variable set consists of scalars, arrays, and hashes.

■ Web server. A computer with special software to hostWeb pages and Web applications. Web servers host static HTML pages, dynamic sites, and a wide variety of applications.

■ WWW (World Wide Web). A subset of the Internet that consists of pages that can be accessed using a Web browser.

Writing Your First CGI Script in Perl

Read the material on writing your first CGI script in Perl on pages 6–11 of your textbook. Follow the instructions onpage 8 to create a Perl CGI script.

Testing and Debugging a Script

Now that you’ve written your first CGI script in Perl, you’llneed to test and debug the script. Follow the instructions on pages 11–12 to test a Perl script from the command line.Follow the instructions on pages 13–14 to test the scriptusing a browser. Follow the instructions on pages 14–15 todebug a Perl script and use the -c switch to locate the error.

Read the Chapter Summary on pages 15–16 and answer theReview Questions on pages 16–18.

Congratulations! You’ve finished the first assignment. Afteryou’ve completed Self-Check 1 and are confident that youunderstand the material presented in this assignment, moveon to Assignment 2.

Programming in CGI/Perl14

ASSIGNMENT 2: SENDING DATAUSING A HYPERLINKRead this introduction and the learning objectives on page 21of CGI/Perl. Then read Chapter 2, pages 21–37, in the text-book. When you’ve completed the material, take the self-checkthat appears at the end of Assignment 2.

Creating a Link to a Script

Carefully read the material on how to create a link to a scripton pages 22–24 of your textbook. It’s important to rememberthat the shebang line is required in Perl CGI scripts that run

Self-Check 1

At the end of each section of Programming in CGI/Perl, you’ll be asked to pause and check your understanding of what you’ve just read by completing a “Self-Check” exercise.Answering these questions will help you review what you’ve studied so far. Please completeSelf-Check 1 now.

1. True or False? You can create, run, and test CGI/Perl scripts on a Unix server, on theWindows operating system, and on the Macintosh operating system.

2. What do the perl -c scriptname and perl -w scriptname commands do?

__________________________________________________________________________

__________________________________________________________________________

3 The shebang line begins with _______.

4. The _______ defines how a server communicates with CGI scripts or programs.

5. True or False? Unix and Perl commands are not case sensitive.

Check your answers with those on page 75.

Lesson 1 15

on a Unix system, and it must be the first line in the script.In this course, the graded projects require that your scriptsoperate on a Unix server.

Follow the instructions on pages 23–24 to create the Jackson Elementary School Web page and begin creating the jackson.cgi script.

The print FunctionRead the material on the print function on pages 24–27 ofyour textbook. You’ll use the print function to generate ascript’s output. Reference Figure 2-3 for examples of how to use the print function in a Perl statement.

File permissions can be set on the Unix server via a Telnetclient or an FTP client. The permission “755” (rwxr-xr-x),which allows the script to be executed when called to abrowser, is the most common permission setting for CGIfiles.

Follow the instructions on page 25 to complete the jackson.cgiscript from the command line. Follow the instructions onpages 26–27 to test the four links contained on the JacksonElementary School Web page.

Sending One Item of Data Using a LinkRead the material on how to send one item of data using alink on pages 27–29 of your textbook. When you use a linkto send data, you’ll append the data to the link’s URL that’sspecified in the anchor tag’s HREF property. ReferenceFigure 2-7 for the syntax and examples of how to send onedata item using a link. Follow the instructions on pages28–29 in your textbook to send the state name using a link.

Parsing DataRead the material on parsing data on pages 29–34 of yourtextbook. Follow the instructions on page 30 to use theCGI.pm module’s standard features in the jackson.cgi script.Follow the instructions on pages 30–32 to modify and testthe message displayed by the jackson.cgi script. Follow theinstructions on pages 33–34 to test the jackson.cgi scriptfrom the jackson.html Web page.

Programming in CGI/Perl16

Sending Multiple Items of Data Using a Link

Read the material on sending multiple items of data using alink on pages 34–37 of your textbook. Follow the instructionson pages 34–36 to modify the jackson.html and jackson.cgifiles. Follow the instructions on pages 36–37 to test the jackson.cgi script from the jackson.html Web page.

Read the Chapter Summary on page 37 and answer theReview Questions on pages 37–39. Then complete Self-Check 2. After you’ve completed the self-check and are confident that you understand the material presented in this assignment, move on to Assignment 3.

Self-Check 21. When using the CGI.pm module to parse a script’s incoming data, what statement must be

included in the script?

__________________________________________________________________________

__________________________________________________________________________

2. In the CGI.pm statement that’s used to parse a script’s incoming data, what does qw standfor?

__________________________________________________________________________

__________________________________________________________________________

3. What is one example of a commonly used import tag?

__________________________________________________________________________

4. What is the most common permission setting for CGI files?

__________________________________________________________________________

5. True or False? A param key must be enclosed with single quotations.

Check your answers with those on page 75.

Lesson 1 17

ASSIGNMENT 3: SENDING DATAUSING AN ONLINE FORMRead this introduction and the learning objectives on page 43of CGI/Perl. Then read Chapter 3, pages 43–69, in the textbook.When you’ve completed the material, take the self-check thatappears at the end of Assignment 3.

Processing Form Data

Read the material on processing form data on pages 44–45 of your textbook. This section provides an overview of howforms are processed. Reference Figure 3-3 on page 45 for anillustration of this process.

Planning the Bonus Calculator Script

Read the material on planning the Bonus Calculator scripton pages 45–46 of your textbook. Reference Figure 3-4 onpage 46 for the input, output, and algorithm of the BonusCalculator script.

Variables and Assignment Statement in Perl

Read the material on variables in Perl on pages 46–49 ofyour textbook. In Perl, variables are used to temporarily storedata that’s parsed from a form.

Perl supports three data types:

■ Scalar variables ($)—Store only one value, which is typically a number or string

■ Array variables (@)—Store lists of values

■ Hash variables (%)—Store sets of values

Programming in CGI/Perl18

In general, Perl doesn’t require you to explicitly declare the variables used in any given script. Instead, variables are created on-the-fly or when they’re used by the script. Perl offers a method to prevent the creation of undeclaredvariables: use strict.

When working with variables, you’ll use assignment state-ments to assign a value to or change the value stored in an existing variable. Reference Figure 3-5 on page 48 forexamples of assignment statements.

Coding the Bonus Calculator Script

Read the material on coding the Bonus Calculator script on pages 49–54 of your textbook. In this section, you’ll create the Bonus Calculator script. This script uses fourscalar variables:

■ Three variables to store the input items: name, salesamount, and bonus rate

■ One variable to store the bonus amount

Follow the instructions on page 49 to prevent Perl from cre-ating undeclared variables, and then declare the variables in the Bonus Calculator script. Follow the instructions onpage 50 to assign sample values to the input variables.

Reference Figure 3-8 on page 51 for a list of Perl arithmeticoperators and their order of precedence. Follow the instruc-tions on pages 52–54 to calculate the bonus amount, assignthe result of a variable, and complete and test the dynamicWeb page.

Accessing the Values Received from an Online Form

Read the material on accessing values received from anonline form on pages 54–57 of your textbook. When data is passed to a script from an online form, the key/value combinations are passed and then parsed. If you’re sendingmultiple words using a hyperlink, spaces between words arereplaced by a plus sign (+).

Lesson 1 19

Follow the instructions on pages 55–57 to parse the data sentby the Bonus Calculator form and use the param function toaccess the form values.

The Bonus Calculator Form

Read the material on the Bonus Calculator form on pages57–60 of your textbook. Follow the instructions on pages57–60 to complete the code for the Bonus Calculator form.

Including a Dollar Sign in a Number

Read the material on pages 60–62 to learn how to include adollar sign ($) in a number. Reference Figure 3-19 for exam-ples of including a dollar sign in a print statement. Follow theinstructions on pages 61–62 to include a dollar sign beforethe bonus and sales amounts.

Using the printf Function

Read the material on using the printf function on pages62–68 of your textbook. The printf function is more powerfulthan the print function, because it allows you to format thedata that’s displayed on a Web page. The printf function ismade up of five parts, which are listed in Figure 3-23 onpage 64. Reference Figure 3-24 on page 65 for a detailedsummary of the printf syntax and examples. Follow theinstructions on pages 67–68 to include the printf function in the bonus.cgi script.

Read the Chapter Summary on pages 68–69 and answer the Review Questions on pages 69–71. Then complete Self-Check 3. After you’ve completed the self-check and are confident that you understand the material presented inLesson 1, complete the graded project.

Programming in CGI/Perl20

Self-Check 3

1. What two fields are required by the printf function?

__________________________________________________________________________

__________________________________________________________________________

2. What are the two most commonly used printf function modifiers?

__________________________________________________________________________

__________________________________________________________________________

3. True or False? To display a dollar sign in a script, you must place a front slash in front of thedollar sign in the print statement.

4. _______ operators require one operand.

5. _______ variables are preceded by the @ sign.

Check your answers with those on page 75.

OVERVIEW

Now that you’ve completed all of the assignments in Lesson 1and have read chapters 1 through 3 in your textbook, you’reready to complete the Lesson 1 graded project. Working withCGI and Perl for processing data is an essential part of yourlearning foundation, so this graded project reflects those skills.Throughout this graded project, you’ll use the skills that you’vegained throughout Lesson 1. Pay close attention to all of theinstructions so that your solution will be a success. Rememberto include all of the required components when you submityour solution.

BEFORE YOU BEGIN

As you progress through this graded project, you’ll be requiredto complete a number of tasks in order to create your solution.This graded project is based on Case Project 1 on page 77 ofyour textbook. For this graded project, you’ll create an HTMLform and a CGI script for Lake College. The following instruc-tions have been modified to meet the requirements for theUnix server that you’ll be transferring your files to.

21

Lesson 1Creating Your First CGI/Perl Form

EXAMINATION NUMBER:

40272900Whichever method you use in submitting your exam

answers to the school, you must use the number above.

For the quickest test results, go to http://www.takeexamsonline.com

Exa

min

atio

nE

xam

ina

tion

INSTRUCTIONS

1. Create a HTML document named c03case1.html. Note: Your form action statement should be as follows:

<FORM METHOD="POST" ACTION="/~username/cgi-bin/c03case1.cgi">.

Also, remember to include a Submit button.

2. This HTML form will allow the user to enter the student’s name and the numberof hours the student is enrolled for the semester. Reference pages 57–60 in yourtextbook.

3. Create a CGI script named c03case1.cgi. Reference pages 48–57 in your text-book. Note that the shebang line for the Unix server you’ll be using is as follows:

#!/usr/bin/perl

4. The CGI script should calculate the total due by multiplying the number hoursenrolled by $100 and then adding the room and board fee ($1,800) to the result.Reference pages 50–57 in your textbook.

5. The script should then display the form data and the total due on a Web page.Reference pages 60–68 in your textbook.

6. Transfer the c03case1.html file in binary mode to the public_html area of yourUnix server account and place it in the folder named PerlGPLesson1. You’ll needto create this folder for your project.

7. Transfer the c03case1.cgi script in ASCII mode to the cgi-bin within thepublic_html area of your Unix server account.

8. Set the permissions of the c03case1.cgi to 755.

9. Test your script on the server via your Web browser by typing in the following URL:

http://unix.pennfoster.com/~username/PerlGPLesson1/c03case1.html

Examination, Lesson 122

PROJECT SUBMISSION GUIDELINES

When you’ve completed your graded project, you’ll upload it to the Web hosting site.If you need help, go to http://unix.pennfoster.com/~instructions/. Send yourcourse instructor an e-mail at [email protected] to let him or her know thatyou’ve submitted your project. Name the project folder 40272900.

You’ll need to transfer the HTML file within the public_html area of your Unix serveraccount in a folder named PerlGPLesson1. The CGI script should be transferred tothe cgi-bin within the public_html area. All CGI scripts should be placed directlywithin your cgi-bin without any folders.

GRADING CRITERIA

Your grade for this project will be based on the following items:

Student successfully created HTML form 25 points

Student successfully created the CGI script 25 points

CGI script successfully displayed the form data and the total due as instructed 25 points

Student followed instructions appropriately 5 points

Project works appropriately 20 points

Total 100 points

Examination, Lesson 1 23

NOTES

Examination, Lesson 124

Arrays and Data FilesThis lesson consists of two assignments that correspond toChapters 4 and 5 in your textbook.

OBJECTIVES

When you complete this lesson, you’ll be able to

■ Create arrays

■ Describe the access methods of variables in arrays

■ Explain the repetition structure of the foreach and for statements

■ Create and access variables in a hash

■ Use the print, chomp, split, die, and sort functions

■ Initialize and update counters

■ Open and write records to a file

ASSIGNMENT 4: ARRAY ANDHASH VARIABLESRead this introduction and the learning objectives on page 79of CGI/Perl. Then read Chapter 4, pages 79–101, in the text-book. When you’ve completed the material, take the self-checkthat appears at the end of Assignment 4.

The Product Registration Form and Acknowledgment

Read the material on the product registration form andacknowledgment on pages 80–82 of your textbook. Follow theinstructions in this section to view the HTML code for theJuniper Printers registration form.

25

Le

ss

on

2

L

es

so

n

2

Programming in CGI/Perl26

Planning and Coding the Juniper Printers Script

Read the material on planning and coding the JuniperPrinters script on pages 83–85 of your textbook. Follow theinstructions in this section to complete the juniper.cgi script.Reference Figure 4-5 on page 83 for an overview of the input,output, and algorithm for the Juniper Printers script.

Array Variables

Read the material on array variables on pages 85–89 of yourtextbook. An array is a group of related scalar variables thatall have the same name. Each array variable is identified by aunique number, known as an index or a subscript. ReferenceFigure 4-8 on page 86 to see how statements can be used todeclare an array. Remember that the $ symbol identifies avariable as an individual scalar variable, whereas the @ sym-bol identifies a variable as an array data type. Follow theinstructions on pages 88–89 to use an array in the JuniperPrinters script.

Hash Variables

Read the material on hash variables on pages 89–94 of yourtextbook. A hash, or associative array, is a collection ofscalar variables that are distinguished from each other by a key or name rather than an index number. ReferenceFigure 4-13 on page 90 for an illustration of statements thatdeclare a hash. Remember that the % symbol identifies avariable as a hash data type. It’s also worth noting that a keymust be enclosed within single (') or double (") quotationmarks between the braces if it contains a space. Follow theinstructions on pages 92–94 to use a hash in the JuniperPrinters script.

Modifying the Juniper Printers Form and Script

Read the material on modifying the Juniper Printers formand script on pages 94–96 of your textbook. Follow theinstructions in this section to include check boxes on theJuniper Printers registration form and further modify theJuniper Printers script.

The foreach and for Statements

Read the material on the foreach and for statements on pages 97–100 of your textbook. Many programming languages,including Perl, use repetition structures, or loops. ReferenceFigure 4-21 on page 97 for a summary of the foreach and forstatement syntax and examples.

When using for clauses, the initialization argument for a vari-able is called a counter variable. This enables the for statementto keep track of the number of times the loop instructionsare processed. Follow the instructions on pages 98–100 tocomplete the juniper2.cgi script.

Read the Chapter Summary on page 101 and answer theReview Questions on pages 102–104. Then complete Self-Check 4. After you’ve completed the self-check and are confident that you understand the material presented in this assignment, move on to Assignment 5.

Lesson 2 27

ASSIGNMENT 5: DATA FILESRead this introduction and the learning objectives on page 111of CGI/Perl. Then read Chapter 5, pages 111–137, in the text-book. When you’ve completed the material, take the self-checkthat appears at the end of Assignment 5.

The Super Bowl Form and Acknowledgment

Read the material on the Super Bowl form and acknowl-edgment on pages 112–114 of your textbook. Follow the instructions in this section to view the HTML code used for the Super Bowl form.

Programming in CGI/Perl28

Self-Check 4

1. True or False? A hash is also referred to as a subscript.

2. Identify the symbols that correspond with an array and a hash.

__________________________________________________________________________

__________________________________________________________________________

3. A/An _______ is identified by a unique number.

4. A/An _______ is used to repeat one or more instructions for each element in a group.

5. True or False? You can use the for statement to repeat one or more statements as long asthe loop condition is false.

Check your answers with those on page 75.

Lesson 2 29

Planning and Coding the Super Bowl Script

Read the material on planning and coding the Super Bowl script on pages 114–115 of your textbook. ReferenceFigure 5-4 on page 114 for an overview of the input, output,and algorithm for the Super Bowl script. Follow the instruc-tions on page 115 to complete the super.cgi script.

Working with Data Files

Read the material on creating and opening a file and savingdata to a file on pages 116–118 of your textbook. You’ll usethe open function to create a data file and/or open a data filein a Perl script. This function contains a maximum of threearguments:

■ Filehandle (required)

■ Mode (optional)

■ Filename (required)

Reference Figure 5-6 on page 116 for an overview of the openfunction modes. Also reference Figure 5-7 on page 117 forexamples of using the open function to open files.

Using the die Function

Read the material on the die function on pages 118–120 ofyour textbook. When an error occurs, you may want to dis-play a message and then exit the script. This task can beaccomplished through the use of the die function, which isoften used in conjunction with the open function. ReferenceFigure 5-8 for examples of combining the die function withthe open function. Follow the instructions on page 120 toinstruct the computer to open the survey.txt file for appendand display a message and then exit the script if the filecan’t be opened.

Programming in CGI/Perl30

Writing Records to a File

Read the material on writing records to a file on pages 120–122of your textbook.

You’ll use the print function to write records to a file. Whenwriting to a file record that contains more than one field,note that you’ll need to use a field separator, such as acomma, colon, ampersand, or tab. Reference Figure 5-9 onpage 121 for examples of writing records to a file. Follow theinstructions on pages 121–122 to instruct the computer towrite the Super Bowl data to the survey.txt file.

Closing a File

Read the material on closing a file on pages 122–124 of yourtextbook. Follow the instructions in this section to instructthe computer to close the survey.txt file.

Calculating the Survey Statistics

Read the material on calculating survey statistics on pages124–128 of your textbook. Follow the instructions in thissection to instruct the computer to open the survey.txt forinput. Reference Figure 5-12 for a list of the tasks requiredto calculate the survey statistics.

Reading Records into an Array

Read the material on reading records into an array on pages124–126 of your textbook. Follow the instructions on page 125to read the records for the survey.txt file into an array andthen close the file. Note that the angle operator (< >) tells thecomputer to read each record from the filehandle and storeeach in a scalar variable within an arrayname.

More on the foreach Statement

Read the material on the foreach statement on pages 126–127of your textbook. Follow the instructions on page 127 tobegin coding the loop illustrated in Figure 5-12 on page 124.

The chomp and split Functions and Counters

Read the material on the chomp and split functions andcounters on pages 127–131 of your textbook. The chompfunction is used to remove the invisible newline characters,represented by \n, from the end of a record. The split func-tion allows you to split or divide a string of characters intoseparate parts based on a pattern. Reference Figure 5-15 onpage 128 for examples of the split function. A counter is avariable that can be used to keep track of a variety of actionsthat take place within a script.

Follow the instructions on page 127 to remove the newlinecharacter from the current record. Follow the instructions on page 129 to split the current record into fields and assign each field to a variable. Follow the instructions onpages 130–131 to initialize and update the counters.

Completing the Super Bowl Script

Read the material on completing the Super Bowl script onpages 131–135 of your textbook. Follow the instructions onpage 131 to display the values stored in the @game_countarray. Follow the instructions on pages 133–135 to completeand test the super.cgi script.

The keys function returns an unordered list of the keys thatare stored in the hash. The sort function returns a alphabet-ized list of the hash’s keys, which is temporary but very useful.

Lesson 2 31

Read the Chapter Summary on pages 136–137 and answerthe Review Questions on pages 137–139. Then complete Self-Check 5. After you’ve completed the self-check and areconfident that you understand the material presented inLesson 2, take the examination for this lesson.

Programming in CGI/Perl32

Self-Check 5

1. A description of the error that causes the open function to fail is stored in the _______ variable.

2. True or False? The beginning value of a counter is always zero.

3. After the _________ function processes, the script is automatically closed.

4. What are two field separators that can be used in the print function?

__________________________________________________________________________

__________________________________________________________________________

5. What are the three open function modes? Briefly explain why you would use the mode set-ting in your open function statement.

__________________________________________________________________________

__________________________________________________________________________

__________________________________________________________________________

Check your answers with those on page 76.

1. Which of the following is not true with regards to the following statement?

NAME=John+Doe&Serial=123456&System=M

A. Data was collected via an online form from a Macintosh computer.

B. Data was sent to the server when the user pressed the Submit button.

C. Data was processed by a CGI script.D. Data was sent to the server using the GET method.

2. A/An _______ is a unique number that distinguishes one scalarvariable from another in an array.

A. array variable C. keyB. primary key D. index

33

Lesson 2Arrays and Data Files

When you feel confident that you have mastered the material in Lesson 2, go to http://www.takeexamsonline.com and submit youranswers online. If you don’t have access to the Internet, you canphone in or mail in your exam. Submit your answers for this examina-tion as soon as you complete it. Do not wait until another examina-tion is ready.

Questions 1–20: Select the one best answer to each question.

EXAMINATION NUMBER:

40273000Whichever method you use in submitting your exam

answers to the school, you must use the number above.

For the quickest test results, go to http://www.takeexamsonline.com

Exa

min

atio

nE

xam

ina

tion

3. In the following expression, what would be used to separate list values?

my arrayname = (list)

A. ; C. :B. , D. |

4. Which of the following marks the beginning of a hash name?

A. @ C. $B. % D. #

5. Which of the following is not true of scalar variables?

A. In an array, scalar variables are stored in order in the computer’s memory.B. In a hash, scalar variables are stored in order in the computer’s memory.C. A scalar variable contained in a hash starts with a $.D. Scalar variables are assigned keys when the hash is created in the

computer’s memory.

6. Which of the following statements is not an example of a repetition structure that instructsthe computer to repeat a block of instructions?

A. foreach C. Nested foreachB. for D. while

7. Which of the following is used by the for statement to keep track of the number of timesthe loop instructions have been processed?

A. Repetition variable C. Counter conditionB. Loop variable D. Counter variables

8. Which of the following is used to allow a script to read data stored in a file?

A. < C. >>B. > D. > and >>

9. Which of the following places an invisible newline character at the end of a record?

A. |n C. \nB. \t D. n;

10. Which of the following is the angle operator in Perl?

A. {} C. ^^B. <> D. !?

Examination, Lesson 234

11. Which of the following syntax statements would write a record to an open file?

A. print filehandle\n;B. print filehandle data filename\n;C. print filename data\n;D. print filehandle data\n;

12. Which of the following occurs if you’re writing to a file named “project” and a file named“project” already exists on your computer?

A. An error message will appear.B. The file will be erased before the new data is written to the file named “project.”C. Two files named “project” will be saved to your computer.D. The computer will prompt you for an alternate name for the data to be saved under

because a file named “project” already exists.

13. What will the following statement do?

open(DATA, ">>", "employees.txt");

A. Open the employees.txt file for output and assign the filehandle DATA to the fileB. Open the employees.txt file for input and assign the filehandle DATA to the fileC. Open the employees.txt file for append and assign the filehandle DATA to the fileD. Open the employees.txt file for append and rename the filename to DATA

14. Which of the following would not be an appropriate field separator for the name field formatted “Doe, John”?

A. : C. ,B. \t D. &

15. Which of the following is an appropriate example of the close function?

A. close(studentdata) C. close{studentdata}B. close<studentdata> D. close[studentdata]

16. The values of a list are sorted

A. permanently.B. in ascending alphabetical order.C. in descending alphabetical order.D. temporarily, according to the designated order.

17. Within which of the following is an array’s index placed?

A. {} C. ()B. [] D. <>

Examination, Lesson 2 35

18. Which of the following is used to display a message when an error occurs?

A. exit C. abortB. quit D. die

19. If numeric and string values are assigned to radio buttons in an HTML form, which of thefollowing is true?

A. The script contains an array.B. The script contains a hash.C. The script contains both an array and a hash.D. The script contains a dynamic Web page.

20. Which of the following is correct?

A. print filehandle data\n; C. print filename data\n;B. print filehandle, data\n; D. print filename, data;

Examination, Lesson 236

Selection Structure and FunctionsThis lesson consists of two assignments that correspond toChapters 6 and 7 in your textbook.

OBJECTIVES

When you complete this lesson, you’ll be able to

■ Describe the Perl if statement selection structure

■ Validate data passed to a script

■ Add items to an array using the push function

■ Create and call a user-defined function

■ Use the exit statement

■ Pass information to and receive information from a user-defined function

■ Access the contents of an environment variable

ASSIGNMENT 6: THE SELECTION STRUCTURERead this introduction and the learning objectives on page 147of CGI/Perl. Then read Chapter 6, pages 147–172, in the text-book. When you’ve completed the material, take the self-checkthat appears at the end of Assignment 6.

The Super Bowl Form and Script

Read the material on the Super Bowl form and script onpages 148–151 of your textbook. Reference Figure 6-1 onpage 148 for an illustration of the Super Bowl form, Figure6-2 on page 149 for an illustration of the Super Bowl scriptcreated in Chapter 5, and Figure 6-4 on page 151 to view themodified output and algorithm for the Super Bowl script.

37

Le

ss

on

3

L

es

so

n

3

Coding the Selection Structure in Perl

Read the material on coding the selection structure in Perlon page 152 of your textbook. This section briefly discussesthe structures of the if and ifelse statements.

Comparison Operators

Read the material on comparison operators on pages 152–157of your textbook. This section covers the comparison, or rela-tional, operators that are supported in the Perl programminglanguage. Reference Figure 6-6 on page 153 for a summaryof Perl comparison operators for numeric values. Figure 6-7on page 154 offers a detailed explanation of how to use if statements that contain numeric comparison operators.Figure 6-8 on page 155 offers a summary of the comparisonoperators for string values supported by Perl. Figure 6-9 on page 156 offers a detailed explanation of how to use ifstatements that contain string comparison operators.

Logical Operators

Read the material on logical operators on pages 158–159 ofyour textbook. In this section, logical operators are discussedin detail. The most common logical operators used in Perl are and and or. Figure 6-10 on page 158 offers a summary oftruth tables for the and and or operators. Refer to Figure 6-11on page 159 for an illustration of if statements that use logical operators.

Validating Script Input Data

Read the material on validating script input data on pages159–161 of your textbook. Follow the instructions in thissection to begin coding the Super Bowl algorithm. ReferenceFigure 6-12 on page 160 for an illustration of this algorithm.Reference Figure 6-13 on page 160 for an illustration of theconditions that you can use to validate the game-rating value.

Programming in CGI/Perl38

Adding Items to an Array

Read the material on adding items to an array on pages161–163 of your textbook. You can use the Perl push function to add one or more items to the end of an array.Reference Figure 6-14 on page 161 for the syntax and exam-ples of the push function. Your textbook also offers somevery important tips on adding items to an array on page 161.

Follow the instructions on pages 162–163 to continue codingthe Super Bowl algorithm.

Determining the Size of an Array

Read the material on determining the size of an array onpages 163–164 of your textbook. Review the tips on page 163that describe the methods you can use to determine the sizeof an array.

Follow the instructions on page 164 and continue coding theSuper Bowl algorithm.

Completing the Super Bowl Script

Read the material on completing the Super Bowl script onpages 164–169 of your textbook. Follow the instructions inthis section to complete and test the Super Bowl script.

Using the if/elsif/else Form of the if Statement

Read the material on the if/elsif/else form of the if statementon pages 169–172 of your textbook. Reference Figure 6-22 onpage 171 for an illustration of two versions of the if statement.

Read the Chapter Summary on page 172 and answer theReview Questions on pages 172–175. Then complete Self-Check 6. After you’ve completed the self-check and are confident that you understand the material presented in this assignment, move on to Assignment 7.

Lesson 3 39

ASSIGNMENT 7: USER-DEFINED FUNCTIONSRead this introduction and the learning objectives on page 181of CGI/Perl. Then read Chapter 7, pages 181–206, in the text-book. When you’ve completed the material, take the self-checkthat appears at the end of Assignment 7.

Functions

Read the material on functions on pages 182–183 of yourtextbook. This section is an introduction to Perl functions,which are also called subroutines. A function is basically a

Programming in CGI/Perl40

Self-Check 6

1. Which comparison operator has the least precedence?

__________________________________________________________________________

2. True or False? Perl comparison operators for string values must be all lowercase letters.

3. True or False? When determining the size of an array, you’re basically determining the num-ber of variables in the array.

4. Identify the elements that an if statement can contain.

__________________________________________________________________________

__________________________________________________________________________

5. True or False? You can add or insert items at the beginning, end, and middle of an array.

Check your answers with those on page 76.

block of code that begins with the Perl keyword sub, which isan abbreviation for “subroutine.” The section introduces thepush, param, and length functions.

Creating a User-Defined Function

Read the material on creating a user-defined function onpages 183–191 of your textbook. When creating a user-defined function, you must follow a few rules. For instance, a function must contain the following:

■ Function header. The function header begins with thekeyword sub followed by a space and then the name ofthe function, another space, and an opening brace ({).

■ Function footer. The closing brace (}).

The function may also include the function body, which caninclude a return statement.

Reference pages 184–191 for examples of programming with functions.

The International Coffees Form andDynamic Web Pages

Read the material on the International Coffees form anddynamic Web pages on pages 191–194 of your textbook. Inthis section, you’ll explore the form International Coffeesuses to gather comments about the coffee it sells. ReferenceFigure 7-6 on page 191 for an overview of the form. Page 192discusses the dynamic aspects of this Web page. Follow theinstructions on page 193 to view the HTML code used to createthe International Coffees form.

Environment Variables

Read the material on environment variables on pages194–195 of your textbook. Environment variables are oftenused in forms to learn more about a variety of things,

Lesson 3 41

such as the server, the user, and so on, when the script isprocessed. Reference Figure 7-12 on page 195 for a list ofcommonly used environment variables.

Coding the International Coffees Script

Read the material on coding the International Coffees scripton pages 195–202 of your textbook. Follow the instructionsin this section to complete the main section of the Internat-ional Coffees script, enter the missing function definitions tocomplete the script, and then test the script.

The while and until Statements

Read the material on the while and until statements on pages202–205 of your textbook. The while and until statementsallow you to repeat a block of instructions while a conditionis true or until a condition becomes true. Refer to Figure 7-17on page 203 for an illustration of the syntax and examples ofthe while and until statements. Follow the instructions tomodify and test the International Coffees script.

Read the Chapter Summary on pages 205–206 and answerthe Review Questions on pages 206–208. Then complete Self-Check 7. After you’ve completed the self-check and areconfident that you understand the material presented inLesson 3, take the examination for this lesson.

Programming in CGI/Perl42

Lesson 3 43

Self-Check 7

1. What elements must be included in a user-defined function?

__________________________________________________________________________

__________________________________________________________________________

2. What is included in the function body?

__________________________________________________________________________

3. True or False? You would use an environment variable if you wanted to know the usernameand password for your account.

4. With what must a function begin?

__________________________________________________________________________

5. True or False? A function can return only one value to the statement that called it.

Check your answers with those on page 76.

NOTES

Programming in CGI/Perl44

1. Which of the following is not true of the if statement?

A. The if clause evaluates the true condition.B. The else clause evaluates the true condition.C. Braces ({}) are required around the statements

being processed.D. The else clause is optional.

2. Comparison operators are also known as _______ operators.

A. arithmetic C. relationalB. logical D. precedence

45

Lesson 3Selection Structure and Functions

When you feel confident that you have mastered the material in Lesson 3, go to http://www.takeexamsonline.com and submit youranswers online. If you don’t have access to the Internet, you canphone in or mail in your exam. Submit your answers for this examina-tion as soon as you complete it. Do not wait until another examina-tion is ready.

Questions 1–20: Select the one best answer to each question.

EXAMINATION NUMBER:

40273100Whichever method you use in submitting your exam

answers to the school, you must use the number above.

For the quickest test results, go to http://www.takeexamsonline.com

Exa

min

atio

nE

xam

ina

tion

3. Which of the following comparison operators has a precedence of 2?

A. == C. >=B. <= D. >

4. Which of the following is not true of string comparison operators?

A. String comparison operators are always lowercase letters.B. Strings are compared based on their ASCII value.C. ‘Apple’ is considered to be greater than ‘baby.’D. Strings that contain the exact same characters are viewed as being equal.

5. Which of the following is an illegal comparison?

A. "Ace" gt "apple" C. "John" != "Jane"B. "Jane" ne "Bill" D. $quantity == 300

6. Which of the following inserts the number 2 and 20 at the beginning of the @inventory array?

A. @inventory = (@inventory, 2, 20);B. @inventory = (2, 20);C. @inventory = [2, 20, @inventory];D. @inventory = (2, 20, @inventory);

7. Which of the following functions is used to add one or more items to an array?

A. print C. pullB. push D. param

8. Which of the following does not return a value?

A. Subroutines C. Scalar variablesB. Sub statements D. Functions

9. Which of the following is not true of a function?

A. A function is processed when the script is invoked.B. A function always starts with the keyword sub.C. A function returns a value based on specific arguments.D. A function can be user defined.

10. Which of the following environment variables would return “127.49.27.1”?

A. HTTP_HOST C. SERVER_NAMEB. REMOTE_HOST D. SERVER_PROTOCOL

Examination, Lesson 346

11. Which of the following is not true of user-defined functions?

A. They enable programmers to create reusable code.B. They enable programmers to create smaller scripts that are just as powerful as large,

complex scripts.C. They allow programmers to avoid writing and testing the same code more than once.D. They allow large scripts to be broken into small, manageable tasks.

12. Which of the following is true of environment variables?

A. They’re constantly running in the background.B. They can be both visible and hidden.C. They’re visible only.D. They’re hidden only.

13. Which of the following is an example of a comparison operator?

A. NE C. ==B. >= D. eq

14. Which of the following accesses the value of the function’s key argument and returns thevalue to the statement that involved the function?

A. push C. paramB. sub D. pull

15. If the array @zipcode contains two elements (37909 and 37920), how would the statementpush(@zipcode, "37919"); change the @zipcode array?

A. The @zipcode array would contain two elements.B. 37919 would be deleted from the @zipcode array.C. 37919 would be added to the @zipcode array.D. The @zipcode array would contain 37919 only.

16. Which of the following statements determines the number of scalar variables contained inthe @class array?

A. scalar(@class) C. $size(@class)B. size(scalr@class) D. scalar(size@class)

17. Which of the following enclose statements processed in an if statement?

A. () C. []B. {} D. " "

18. Which of the following ends the function header?

A. ; C. return expressionB. } D. sub

Examination, Lesson 3 47

Review the following code and answer Questions 19 and 20.

19. Which section represents the main section of the script?

A. A C. CB. B D. D

20. Which of the following is not available to the entire script?

A. $class1 C. $studentsB. $class2 D. $total

Examination, Lesson 348

FIGURE A—Use this illustra-tion to answer Questions 19and 20.

String Manipulation andDBM DatabasesThis lesson consists of two assignments that correspond toChapters 8 and 9 in your textbook.

OBJECTIVES

When you complete this lesson, you’ll be able to

■ Use the uc, lc, and substr Perl functions

■ Locate a string within another string using the index function

■ Explain how to pattern match using the matching operator

■ Include metacharacters in a search pattern

■ Create, open, and add records to a DBM database

■ Connect or link strings (concatenate)

■ Create a “here” document

ASSIGNMENT 8: STRING MANIPULATIONRead this introduction and the learning objectives on page 215of CGI/Perl. Then read Chapter 8, pages 215–243, in the text-book. When you’ve completed the material, take the self-checkthat appears at the end of Assignment 8.

The uc and lc Functions

Read the material on the uc and lc functions on pages216–218 of your textbook. Reference Figure 8-1 on page 217for an overview of the syntax, purpose, and examples of theuc and lc functions. The uc and lc functions are used to

49

Le

ss

on

4

L

es

so

n

4

convert letters in a string to all uppercase (uc) or all lower-case (lc). Note that the ucfirst function can be used to convertthe first character of a string to uppercase.

The substr Function

Read the material on the substr function on pages 218–220of your textbook. The substr function can be used to

■ Return a portion of a string in another string

■ Replace one or more characters in a string with other characters

■ Insert one or more characters within a string

Reference Figure 8-2 on page 219 for a detailed overview ofthe three versions of the substr function and examples ofeach version.

The index Function

Read the material on the index function on pages 220–222 ofyour textbook. The index function is used to search a stringto determine if it contains another string. The index functionautomatically begins the search with the first character inthe string. However, if you omit the start argument in theindex function, it will begin the character at the 0 position.Reference Figure 8-3 on page 221 for an overview of the syntax, purpose, and examples of the index function. Notethat Perl also offers the rindex function, which returns theposition of the last occurrence of the substring within thestring beginning at position start.

The Transliteration and “Contains” Operators

Read the material on the transliteration and “contains” oper-ators on pages 222–226 of your textbook. The transliterationoperator (tr///), which is also referred to as the tr operator,

Programming in CGI/Perl50

is used to replace a character in a string with a differentcharacter. Reference Figure 8-4 on page 223 for an overviewof the syntax and purpose of the tr/// operator.

The tr/// operator is used in conjunction with the “contains”operator (=~), which is also known as the binding operator.When used in this manner, the “contains” operator tells thetr/// operator to search the string to determine if it containsany of the characters listed in the searchlist. When using thetr/// operator, you can take advantage of three modifiers:

■ d

■ c

■ s

Refer to Figure 8-5 on page 224 for examples that demonstratethe use of the tr/// operator without a modifier. ReferenceFigure 8-6 on page 225 for examples that demonstrate theuse of the tr/// operator with a modifier. Reference page 226for a detailed overview of the three modifiers at your disposal.

The Match Operator

Read the material on the match operator on pages 226–228 of your textbook. You can use the Perl match operator (m//),which is also referred to as the m operator, to determine ifone string is contained within another string. ReferenceFigure 8-7 on page 227 for a detailed overview of the syntax,purpose, and examples of the m// operator.

This section also introduces you to the “does not contain”operator (!~). This operator is used to determine if a search-pattern isn’t contained in a string.

Using Metacharacters in a Search Pattern

Read the material on using metacharacters in a search-pattern on pages 229–232 of your textbook. Metacharactersare used in the m// (match) operator’s searchpattern andalso in the s/// (substitution) operator’s searchpattern.

Lesson 4 51

Reference Figure 8-8 on page 229 for a summary of the most commonly used metacharacters and their purposes.Reference Figure 8-9 on page 230 for examples that show theuse of metacharacters in the m// operator’s searchpattern.

Note that a metacharacter must be followed by a wordboundary character, such as a period, comma, or space.Letters, numbers, and underscores are not considered wordboundary characters.

The Substitution Operator

Read the material on the substitution operator on pages232–234 of your textbook. The Perl substitution operator(s///), or s operator, is used for the following:

■ To replace one or more characters in a string with other characters

■ To remove one or more characters from a string

Reference Figure 8-11 on page 233 for a detailed overview ofthe syntax, purpose, and examples of the s/// operator.

The International Coffees Form and Script

Read the material on the International Coffees form andscript on pages 234–243 of your textbook. Follow theinstructions on pages 235–241 to modify the InternationalCoffees script. Follow the instructions on pages 241–243 totest the inter.cgi script.

Read the Chapter Summary on page 243 and answer theReview Questions on pages 244–248. Then complete Self-Check 8. After you’ve completed the self-check and are confident that you understand the material presented in this assignment, move on to Assignment 9.

Programming in CGI/Perl52

Lesson 4 53

Self-Check 8

1. True or False? Alphanumeric characters can be letters, numbers, or underscores.

2. List the three modifiers that can be used with the tr/// operator, and briefly describe the function of each.

__________________________________________________________________________

__________________________________________________________________________

__________________________________________________________________________

3. What connects the string that appears on the left side of the operator to the expression thatappears on the right side?

__________________________________________________________________________

4. Identify the required elements for the tr/// operator.

__________________________________________________________________________

5. True or False? \S matches a nonwhitespace character.

Check your answers with those on page 76.

ASSIGNMENT 9: DBM DATABASESRead this introduction and the learning objectives on page 255of CGI/Perl. Then read Chapter 9, pages 255–278, in the text-book. When you’ve completed the material, take the self-checkthat appears at the end of Assignment 9.

The Jeffrey Sikes Band Form

Read the material on the Jeffrey Sikes Band form on pages 256–261 of your textbook. Follow the instructions on pages 256–258 to view the HTML code used to create the Jeffrey Sikes Band form.

Reference Figure 9-6 on page 259 for an overview of theinput, output, and algorithms for the Jeffrey Sikes Bandscript. Follow the instructions on pages 260–261 to finishcoding the main section’s algorithm in the band.cgi script.

Creating and Opening a DBM Database

Read the material on creating and opening a DBM databaseon pages 261–265 of your textbook. When working with DBMdatabases, it’s important that you understand the following:

■ You must identify the name of the DBM database thatwill be opened or created in a use statement.

■ You use the tie function to open or create a DBM database.

Review the tips in this section for invaluable hints on work-ing with DBM databases. Reference Figure 9-8 on page 262for an overview of the tie function.

Adding a Record to and Modifying aRecord in a DBM Database

Read the material on adding a record to a DBM databaseand on modifying a DBM database record on pages 265–267of your textbook. Reference Figure 9-9 on page 264 for exam-ples of using the tie and die functions to create and open aDBM database.

Follow the instructions on page 265 to tie a database namedmaillist to a hash named %mail.

Reference Figure 9-10 on page 266 for examples of statementsthat either add or modify a record. Follow the instructions onpages 266–267 to add the user’s name and e-mail address tothe mailing list database.

Programming in CGI/Perl54

Closing a DBM Database

Read the material on closing a DBM database on pages267–268 of your textbook. When closing a DBM database,you’ll use the untie function, which removes the tie that bindsthe database to the hash. Follow the instructions on pages267–268 to complete the add function in the band.cgi script.

Completing the remove Function’s CodeRead the material on completing the remove function’s code onpage 269 of your textbook. Reference Figure 9-12 on page 269for an overview of the remove function’s algorithm.

Determining Whether a Specific Key IsContained in a DBM DatabaseRead the material on how to determine whether a specifickey is contained in a DBM database on pages 269–270 ofyour textbook. To determine whether a specific key is con-tained in a DBM database, you’ll use the exists function.Follow the instructions on page 270 to determined if a specific e-mail address is in the maillist database.

Deleting a Record from a DBM DatabaseRead the material on deleting a record from a DBM databaseon page 270 of your textbook. Follow the instructions in thissection to delete a record from the maillist database.

Concatenating StringsRead the material on concatenating strings on pages 270–276of your textbook. Concatenation refers to the connecting orlinking of strings. In Perl, you’ll concatenate strings with aperiod (.), which is referred to as the concatenation operator.Reference Figure 9-13 on page 271 for examples that demon-strate the use of the Perl concatenation operator.

Lesson 4 55

Follow the instructions on pages 271–276 to assign theappropriate message to the $msg variable, test the script’sremove function, and test the band.cgi script.

Creating a “Here” Document

Read the material on how to create a “here” document onpages 276–277 of your textbook. A “here” document allowsyou to use one print statement, rather than multiple printstatements in a script, to print a block of HTML code.Reference Figure 9-16 on page 276 for an overview of thesyntax and examples of a “here” document.

Note: To prevent variable interpolation from occurring in a“here” document, you must enclose the label in single quotation marks.

Read the Chapter Summary on pages 277–278 and answerthe Review Questions on pages 378-280. Then complete Self-Check 9. After you’ve completed the self-check and areconfident that you understand the material presented inLesson 4, take the examination for this lesson.

Programming in CGI/Perl56

Lesson 4 57

Self-Check 9

1. Identify the required elements of the tie function.

__________________________________________________________________________

__________________________________________________________________________

2. List the four tie function flags and their meanings.

__________________________________________________________________________

__________________________________________________________________________

__________________________________________________________________________

3. True or False? The label line of a “here” document must begin in column 1 for the script towork correctly.

4. True or False? A primary key can be made of only one field.

5. Identify the three letters that can come before DBM in the module name. What does eachletter mean?

__________________________________________________________________________

__________________________________________________________________________

Check your answers with those on page 77.

NOTES

Programming in CGI/Perl58

1. Which of the following converts all instances of “yes” to “Yes” inthe variable $answer?

A. $answer = lc($answer);B. $answer = uc($answer);C. $answer = ucfirst(lc($answer));D. $answer = ucfirst(uc($answer));

59

Lesson 4String Manipulation and DBM Databases

When you feel confident that you have mastered the material in Lesson 4, go to http://www.takeexamsonline.com and submit youranswers online. If you don’t have access to the Internet, you canphone in or mail in your exam. Submit your answers for this examina-tion as soon as you complete it. Do not wait until another examina-tion is ready.

Questions 1–20: Select the one best answer to each question.

EXAMINATION NUMBER:

40273200Whichever method you use in submitting your exam

answers to the school, you must use the number above.

For the quickest test results, go to http://www.takeexamsonline.com

Exa

min

atio

nE

xam

ina

tion

2. Which of the following replaces Smith with Jones, resulting in a variable storing Connie Jones?

A. $name = "Connie Smith"; substr($name,0,7) = "Jones";B. $name = "Connie Smith"; substr($name,7,5) = "Jones";C. $name = "Connie Smith"; substr($name,0,0) = "Jones";D. $name = "Connie Smith"; substr($name,7) = "Jones";

3. Which of the following functions takes you to the position of the last substring occurrence,with the string beginning at position start?

A. index C. substrB. rindex D. subindex

4. Which of the following is used to replace a character in a string with a different character?

A. tr// C. tr\\\B. tr=~ D. =~tr

5. Which of the following is known as the “does not contain” operator?

A. ~! C. ~=B. !~ D. =~

6. Which of the following is used to match the beginning of a string?

A. $ C. ^B. ~ D. \b

7. Which of the following is the best function to use to create and open a DBM database on a disk?

A. dbmopen C. tie B. open D. bind

8. Which of the following is used to determine if a specific key is contained in a DBM database?

A. search C. findB. exists D. searchpattern

9. Which of the following is used to exit a script when the tie function fails?

A. exit C. dieB. quit D. untie

10. Which of the following is the string concatenation operator?

A. ! C. !=B. ~ D. period (.)

Examination, Lesson 460

11. What is SDBM_File module an abbreviation for?

A. Standard Perl Database ModuleB. Special Perl Database ModuleC. System Perl Database ModuleD. Simple Perl Database Module

12. Which of the following signifies the end of a string?

A. ^ C. $B. \e D. period (.)

13. What does the index function return if the substring is not contained within the string?

A. 0B. 1C. A number that indicates the end of the string evaluatedD. –1

14. Which of the following is not true of the substitution operator?

A. It can be used to replace one or more character in a string.B. It can be used to delete only one character in a string.C. It’s referred to as s/// operator.D. It’s referred to as the s operator.

15. Which of the following are considered word boundary characters?

A. Letters C. TabsB. Numbers D. Spaces

16. Which of the following tells Perl to replace all characters that are not the uppercase lettersA–Z with a bang character in the middle initial field?

A. $middleinitial =~ tr/A-Z/~/c;B. $middleinitial =~ tr/a-z/*/c;C. $middleinitial =~ tr/A-Z/!/c;D. $middleinitial =~ tr/A-Z/#/c;

17. Which of the following is not required when using the substitution operator syntax?

A. string C. searchpatternB. =~ D. replacementlist

Examination, Lesson 4 61

18. Which of the following would be the result of the following statement?

A. Information Science C. SIS490B. Computer Science D. CS

19. Which of the following does not contain a replacementlist?

A. $course = "CS101"; $course =~ s/CS/Computer Science/g;B. $name = "Jimmy Smith"; $name =~ s/Jimmy/Jim/;C. $price = "$56.75"; $prince =~ s/$//;D. $status = "A"; $status =~ s/A/I;

20. Which of the following is not true of a “here” document?

A. You must enclose a label within single quotation marks.B. The label line can begin in any column.C. All HTML code in a “here” document is printed verbatim.D. If you begin in column 5 of the script, the resulting Web page’s source code is viewed

in column 5 when viewed in a browser

Examination, Lesson 462

FIGURE B—Use this illustration toanswer Question 18.

E-mail, Cookies, andRedirectionThis lesson consists of three assignments that correspond toChapters 10, 11, and 12 in your textbook.

OBJECTIVES

When you complete this lesson, you’ll be able to

■ Create a form using a CGI script

■ Send an e-mail message using a script

■ Use a selection list and hidden fields in a script

■ Describe the difference between temporary and persistent cookies

■ Create a cookie

■ Access the information stored in a cookie

■ Include the location and refresh headers in a script

ASSIGNMENT 10: HIDDEN FIELDSAND E-MAILRead this introduction and the learning objectives on page 287of CGI/Perl. Then read Chapter 10, pages 287–302, in the text-book. When you’ve completed the material, take the self-checkthat appears at the end of Assignment 10.

The Sun Travel Web Pages

Read the material on the Sun Travel Web pages on pages288–290 of your textbook. Follow the instructions in thissection to view the HTML code used to create the BrochureRequest form. Note that a selection list is a commonly usedlist box from which the user can select a particular value orset of values.

63

Le

ss

on

5

L

es

so

n

5

Planning and Coding the sun1.cgi Script

Read the material on planning and coding the sun1.cgi scripton pages 291–293 of your textbook. Reference Figure 10-5from page 291 for an overview of the input, output, and algo-rithm for the sun1.cgi script. Follow the instructions in thissection to begin completing the sun1.cgi script.

Creating a Hidden Field in a Script

Read the material on creating a hidden field in a script onpages 293–296 of your textbook. A hidden field is a usefulelement that can be included in scripts to gather informationthat’s later passed to the server. This element isn’t visible onthe form; however, it can be viewed in the source code. Referto Figure 10-7 for an overview of the syntax and examples ofusing a hidden field in a form created by a CGI script.

Follow the instructions on pages 294–296 to complete thecoding of the sun1.cgi script.

Planning and Coding the sun2.cgi Script

Read the material on planning and coding the sun2.cgi scripton pages 296–299 of your textbook. Reference Figure 10-10on page 296 for an overview of the input, output, and algo-rithm for the sun2.cgi script. Follow the instructions onpages 297–299 to continue working and testing the sun2.cgiscript.

Using a Script to Send E-mail

Read about using a script to send e-mail on pages 299–302of your textbook. Reference Figure 10-13 on page 299 for anoverview of the Mail::Sendmail module procedure. Follow theinstructions on pages 300–302 to complete and test thesun2.cgi script.

Programming in CGI/Perl64

Read the Chapter Summary on page 302 and answer theReview Questions on pages 302–304. Then complete Self-Check 10. After you’ve completed the self-check and are confident that you understand the material presented in this assignment, move on to Assignment 11.

Lesson 5 65

Self-Check 10

1. List the five keys used in the Mail::Sendmail module.

__________________________________________________________________________

__________________________________________________________________________

2. What is SMTP?

__________________________________________________________________________

__________________________________________________________________________

3. True or False? A hidden field contains a key/value pair.

4. When working with the Mail::Sendmail module, a/an _______ must be created to store the e-mail information.

5. True or False? You can use hidden fields to pass information from one CGI script to another.

Check your answers with those on page 77.

ASSIGNMENT 11: COOKIESRead this introduction and the learning objectives on page 311of CGI/Perl. Then read Chapter 11, pages 311–325, in the text-book. When you’ve completed the material, take the self-checkthat appears at the end of Assignment 11.

Using a Cookie

Read the material on cookies on page 312 of your textbook. A cookie is a piece of data that a Web server can store on acomputer, either in random access memory or on the harddisk. When using cookies, it’s important to understand thedifference between session cookies and persistent cookies.

Session, or temporary, cookies are stored in a computer’sRAM (Random Access Memory) and exist until the Webbrowser is closed. In contrast, a persistent cookie is stored ina text file on the computer’s hard disk and exists until theuser manually deletes it from the computer disk or thecookie deletes itself by use of an expiration date establishedby its programmer.

Creating a Cookie

Read the material on creating cookies on pages 313–315 ofyour textbook. Reference Figure 11-1 on page 313 for anoverview of the syntax of the cookie function used to create a cookie. The cookie function has four arguments:

■ -name

■ -value

■ -path

■ -expires

Reference Figure 11-2 on page 314 for examples that demon-strate the use of the cookie function to create a cookie.

Programming in CGI/Perl66

Sending a Cookie to the Browser

Read the material on sending a cookie to a browser on pages 315–316 of your textbook. To send a cookie to abrowser, you’ll use the header function, which can be viewedon page 316 in Figure 11-3. It’s very important to place yourprint statements below the Content-type header line. If they’reabove this line, the header function won’t be able to send thecookie to the browser.

Accessing the Information Stored in a Cookie

Read the material on accessing the information stored in acookie on pages 317–318 of your textbook. You can use thecookie function to access the information that’s stored in acookie, as shown in Figure 11-4 on page 317.

The Jubilee Book Club Web Pages

Read the material on the Jubilee Book Club Web pages onpages 318–320 of your textbook. Follow the instructions onpages 319–320 to view the HTML code used to create theJubilee Book Club’s home page.

Planning and Coding the book2.cgi Script

Read the material on planning and coding the book2.cgiscript on pages 320–322 of your textbook. Reference Figure 11-9 on page 320 to review the input, output, andalgorithm for the book2.cgi script. Follow the instructions on pages 321–322 to complete the book2.cgi script.

Lesson 5 67

Planning and Coding the book1.cgi Script

Read the material on planning and coding the book1.cgiscript on pages 322–325 of your textbook. Reference Figure 11-11 for the input, output, and algorithm for thebook1.cgi script. Follow the instructions on pages 323–325 to complete and test the book1.cgi script.

Read the Chapter Summary on page 325 and answer theReview Questions on pages 326–327. Then complete Self-Check 11. After you’ve completed the self-check and are confident that you understand the material presented in this assignment, move on to Assignment 12.

Programming in CGI/Perl68

Self-Check 11

1. True or False? If the expires argument is omitted from the cookie, then the cookie expireswhen the browser is closed.

2. Identify the required arguments for the cookie function.

__________________________________________________________________________

__________________________________________________________________________

3. True or False? You can enclose the key of a cookie within single or double quotation marks.

4. True or False? A cookie can’t pass a virus to your computer.

5. _______ are sent along with the URL you’re requesting.

Check your answers with those on page 77.

ASSIGNMENT 12: REDIRECTIONRead this introduction and the learning objectives on page 333of CGI/Perl. Then read Chapter 12, pages 333–341, in the text-book. When you’ve completed the material, take the self-checkthat appears at the end of Assignment 12.

Redirecting a Browser

Read the material on redirecting a browser on pages 334–335of your textbook. You can use the Location header or theRefresh header to redirect a browser. The Location headerredirects the browser immediately, whereas the Refreshheader redirects the browser after a specified number of seconds have passed.

Using a Refresh Header

Read the material on the Refresh header on pages 335–338of your textbook. Follow the instructions on pages 335–336to observe how the specified files interact. Follow the instruc-tions on pages 337–338 to include a Refresh header in thefulton.cgi script.

Using a Location Header

Read the material on the Location header on pages 338–341of your textbook. Follow the instructions on pages 338–339to observe how the specified files interact. Follow the instruc-tions on pages 340–341 to include a Location header in thecara.cgi script.

Read the Chapter Summary on page 341 and answer the Review Questions on pages 341–343. Then complete Self-Check 12. After you’ve completed the self-check and are confident that you understand the material presented in Lesson 5, complete the graded project for this lesson.

Lesson 5 69

Programming in CGI/Perl70

Self-Check 12

1. When using the Location header or the Refresh header, what must be included so that thescript knows where to send the browser?

__________________________________________________________________________

__________________________________________________________________________

2. When using the Location header or the Refresh header, you must place the redirect information within a/an ________ statement.

3. True or False? If the seconds element isn’t included in the Refresh header, the redirectwon’t function appropriately.

4. The ________ is used with the Content-type header.

5. True or False? When using the Refresh and Location headers, the browser can be sent tothe same location.

Check your answers with those on page 78.

OVERVIEW

Now that you’ve completed all of the assignments in Lesson 5of this study guide and have read Chapters 10, 11, and 12 inyour textbook, you’re ready to complete this graded project.Working with CGI and Perl for processing data are essentialelements of your learning foundation, thus this graded projectreflects those skills. Throughout this graded project, you’lluse the skills that you’ve gained throughout Lesson 5. Payclose attention to all of the instructions so that your solutionwill be a success. Remember to include all of the requiredcomponents when you submit your solution.

BEFORE YOU BEGIN

As you progress through this graded project, you’ll berequired to complete a number of tasks in order to create thissolution. This graded project is based on Case Project 1 onpage 348 of your textbook. For this graded project, you’ll

71

Lesson 5E-mail, Cookies, and Redirection

EXAMINATION NUMBER:

40273300Whichever method you use in submitting your exam

answers to the school, you must use the number above.

For the quickest test results, go to http://www.takeexamsonline.com

Exa

min

atio

nE

xam

ina

tion

create two HTML documents and a CGI script for Phoenix Industries. The followinginstructions have been modified to meet the requirements for transferring files to aUnix server.

INSTRUCTIONS

1. Create an HTML document named c12case1a.html. Note: Your form action statement should be as follows:

<FORM METHOD="POST" ACTION="/~usernname/cgi-bin/c12case1.cgi">

2. The HTML form will allow the user to enter his or her:

■ Name

■ Address

■ City

■ State

■ ZIP code

You’ll need to include a Submit button and a Reset button. Reference pages57–60 in your textbook.

3. Create a CGI script named c12case1.cgi. Reference pages 48–57 in your text-book. Note that the shebang line for the Unix server you’ll be using is as follows:

#!/usr/bin/perl

4. This CGI script should verify that the form data is complete before displaying the data on a Web page. If one or more form entries are blank, the script shouldimmediately redirect the user’s browser to the c12case1b.html document. Hint:Use the Location header to redirect the browser. Reference pages 338–341 inyour textbook.

5. Create a HTML document named c12case1b.html. This document should advisethe user to return to the form to complete all entries using the following state-ment: “Please press your browser’s Back button to return to the form. Then complete all items.” Reference pages 340–341 in your textbook.

6. Transfer the c12case1a.html and c12case1b.html files in binary mode to the public_html area of your Unix server account to the folder namedPerlGPLesson5. If you haven’t already done so, you may need to create thisfolder for your project.

Examination, Lesson 572

7. Transfer the c12case1.cgi script in ASCII mode to the cgi-bin within thepublic_html area of your Unix server account.

8. Set the permissions of the c12case1.cgi to 755.

9. Test your script on the server via your Web browser by typing in the followingURL:

http://unix.pennfoster.com/~username/PerlGPLesson5/c12cast1.html

PROJECT SUBMISSION GUIDELINES

When you’ve completed your graded project, you’ll upload it to the Web hosting site.If you need help, go to http://unix.pennfoster.com/~instructions/. Send yourcourse instructor an e-mail at [email protected] to let him or her know thatyou’ve submitted your project. Name the project folder 40273300.

You’ll need to transfer the HTML file within the public_html area of your Unix serveraccount in a folder named PerlGPLesson5. The CGI script should be transferred tothe cgi-bin within the public_html. All CGI scripts should be placed directly withinyour cgi-bin without any folders.

GRADING CRITERIA

Your grade for this project will be based on the following items:

Student successfully created HTML documents 25 points

Student successfully created the CGI script 25 points

CGI script successfully displayed the form data and redirected as instructed 25 points

Student followed instructions appropriately 5 points

Project works appropriately 20 points

Total 100 points

Examination, Lesson 5 73

NOTES

Examination, Lesson 574

75

An

sw

er

sA

ns

we

rs

Self-Check 1 1. True

2. perl -c scriptname tells the Perl interpreter to check forsyntax errors in the script without running the script.perl -w scriptname tells the Perl interpreter to check forerrors in a script and then run the script.

3. #!

4. CGI protocol

5. False

Self-Check 21. CGI qw(:standard)

2. quote words

3. :standard from the statement 'CGI qw(:standard); '

4. 755

5. False

Self-Check 31. % and format type

2. + and 0

3. False

4. Unary

5. Array

Self-Check 41. True

2. array = @ and hash = %

3. array variable

4. foreach statement

5. False

Self-Check 51. $!

2. False

3. die

4. comma, colon, ampersand, or tab

5. Figure 5-6 on p. 116 lists all possible answers.

Self-Check 61. !=

2. True

3. True

4. Variables, numbers, strings, functions, arithmetic operators, comparison (relational) operators, and logical operators

5. True

Self-Check 71. Function header, function footer

2. return statement

3. False

4. Perl keyword sub

5. False

Self-Check 81. True

2. d modifier, deletes characters as directed; c modifier,replaces characters as directed; s modifier, squashesspaces as directed

Self-Check Answers76

3. binding operator, contains operator, or =~

4. string, "contains" operator, and searchlist

5. True

Self-Check 91. hash, module, filename, flag, and mode

2. O_RDONLY = open the database for reading only;O_WRONLY = open the database for writing only;O_RDWR = open the database for both reading and writ-ing; O_CREAT = create the database if it doesn’t exit

3. True

4. False

5. O = Old; N = New; S = Simple

Self-Check 101. To, From, Subject, SMTP, and Message

2. SMTP stands for Simple Mail Transfer Protocol. It’s usedwhen sending and receiving e-mail.

3. True

4. hash)

5. True

Self-Check 111. True

2. -name and -value

3. True

4. True

5. Cookies

Self-Check Answers 77

Self-Check 121. A URL

2. print

3. True

4. Refresh header

5. True

Self-Check Answers78


Recommended