Lesson 6 -- Printer Friendly Version
INSTRUCTIONS:
IMPORTANT: This version of your lesson is for saving or printing only. All links and images have been disabled to decrease download time and help you avoid printer difficulties.
Chapter 1
In Perl, an array is simply a list of variables. Arrays are used when you need an efficient way to keep track of a large number of variables in your program.Allow me to demonstrate the usefulness of arrays.
Suppose you need to keep track of the first names of a group of six students. You could do so by creating six separate variables--one for each name:
$student0 = "Al";
$student1 = "Betty";
$student2 = "Carl";
$student3 = "Donna";
$student4 = "Eric";
$student5 = "Fran";Or, you could create an array to hold all the student names:
@students=('Al','Betty','Carl','Donna','Eric','Fran');
Both of the methods outlined above would accomplish our goal of storing a collection of student names in memory.
However, notice how the first method we used to store these six names in memory required:
-six lines of code,
-a whopping 114 characters, and
-a tremendous amount of repetition.
Storing the names in an array required only one line of code containing 54 characters. Obviously, you'll save a bit of typing time by substituting the array for the variables.
However, your use of the array will also result in a faster and more efficient program.
Believe it or not, it would take roughly the same amount of processing time for your computer to gobble up ALL the values in the array above as it would take it to create just the first variable to store Al's name.
Therefore, it could take almost six times longer to create six variables containing one student name each than it would to create one array containing six student names.
Two Types of Arrays
Perl permits you to create two different types of arrays:
1. ordinary arrays, in which each variable is referenced by a number that corresponds to its position in the array.
Ordinary arrays always have names that begin with an '@' sign.
The array named '@students' in the example above is an ordinary array. Notice how each variable item in the array is surrounded by single quotes (also known as apostrophes).
Also notice how each item is separated from the next by a comma. In an array (despite what your sixth-grade grammar teacher taught you) the commas go OUTSIDE of the quote marks.
Exercise:
Using pencil and paper, create an ordinary array named @fish that contains the following values:
red snapper salmon orange roughy swordfishSolution: (please don't peek)@fish=('red snapper','salmon','orange roughy','swordfish');2. associative arrays, in which each variable in the array is given a name, called a 'key.'An associative array looks a lot like an ordinary array, except for the fact that each variable in the array is preceded by a key. Associative arrays also always have names that start with a '%' sign. Here's an example of an associative array:
%location=('Name','Mary Perez','Street','4105 Elm Ave', 'City','Tualatin','State','OR','Zip','97062');
Each of the variables in an associative array must be preceded by a name. The variables will be associated with the names that precede them.
In the associative array just above, 'Mary Perez' will be associated with the key 'Name,' '4105 Elm Ave' will be associated with the key 'Street,' 'Tualatin' will be associated with 'City,' 'OR' will be associated with 'State,' and '97062' will be associated with 'Zip.' Exercise:
Using pencil and paper, create an associative array named %prices that associates the items listed below with their price:
Item Price Pet rock 2.95 Smiley button 9.95 Puzzle Cube 11.95
Solution: (please don't peek)%prices=('Pet Rock','2.95','Smiley button','9.95', 'Puzzle Cube','11.95');
Chapter 2
As a web programmer, you will be spending quite a bit of time working with arrays.Arrays and Databases:
Arrays can prove useful if you need to transfer the contents of a file into memory. You might want to do this if you need to verify a password entered on a form against a password stored in a password file, search through a database, check the status of an order or perform any number of other file-related activities.
We will begin working with databases in lesson 9.
Arrays and Form Data:
Arrays are also required for processing form data. If you want to build an interactive web site, forms are going to be involved in one way or another. All the data coming in from the form will be stored in an associative array.
As you learned in lesson 5, a form consists of two or more input devices. Each of these input devices will have a name that is assigned to the input device by you. When a user enters data into these input devices, the data that the user enters must be associated with the name of the input device. The best way to do this is with an associative array.
For example, suppose you have a form on your web site with three text boxes named 'Qty,' 'Size,' and 'Color.'
A user happens to stop by the site and fills out your form. The user types '12' in the box named 'Qty,' 'XXL' in the box named 'Size,' and 'white' in the box named 'Color.'
This incoming form data could then easily be stored in an associative array named %in (or any other name starting with a % sign.) The names of each input devices would become your keys. These keys would be associated with the values the user entered on your form.
Such an associative array might look something like this:
%in=('Qty','12','Size','XXL','Color','white');Exercise:Using pencil and paper, create an associative array named %in that might be formed if a user were to type the following values into the form fields listed below:
form field value Name Joan E. Gilbert City Orinda State California
Solution (try not to peek):%in=('Name','Joan E. Gilbert','City','Orinda', 'State','California');In our next lesson, you will actually write a script that stores the values of a submitted form in an array and redisplays those values on a web page. You will continue working with incoming form data in each of the lessons remaining in this course.
Chapter 3
Extracting a variable from an array is fairly simple, although the procedure differs depending on the type of array in use.Ordinary Array
Each of the variables in an ordinary array is assigned an imaginary number, called an 'index.' The index number for the first variable in an ordinary array is 0, the index number for the second variable in an ordinary array is 1, and so on.
To extract the value of a variable stored in an ordinary array, all you have to do is type a $ sign followed immediately by the name of the array (without the '@' sign). The array name should then be followed by the index number, which needs to be enclosed in [square brackets].
For example, the expression $students[0] would evaluate to 'Al' in the array below. The expression $students[1] would evaluate to 'Betty', the expression $students[2] would evaluate to 'Carl', and so on.
@students=('Al','Betty','Carl','Donna','Eric','Fran');
Likewise, the following statement:
print "<p>Is your name $students[5]?</p>";would produce the following sentence:Is your name Fran?Exercise:What sentence would the following statement produce?
print "<p>Is your name $students[3]?</p>";Solution: (try not to peek)Is your name Donna?Associative ArrayAs I mentioned earlier, each of the variables in an associative array is assigned a key. If you want to extract one of the values in an associative array, all you have to do is type a $ sign followed immediately by the name of the array (without the '%' sign). The array name should then be followed by the key, which needs to be surrounded by 'single quotes' and enclosed in {curly brackets}.
For example, in the array below, the keys are 'Name,' 'Street,' 'City,' 'State,' and 'Zip.'
If the expression $location{'Name'} were applied to the array below, it would evaluate to 'Mary Perez,' the expression $location{'Street'} would evaluate to '4105 Elm Ave,' the expression $location{'City'} would evaluate to 'Tualatin,' and so on.
%location=('Name','Mary Perez','Street','4105 Elm Ave', 'City','Tualatin','State','OR','Zip','97062');
Likewise, the following statement:
print "<p>The zip code in $location{'City'} is $location{'Zip'}.</p>";
would produce the following sentence:
The zip code in Tualatin is 97062.
Exercise:
Given the following associative array:
%dogs=('Snoopy','beagle','Sparky','dalmation', 'Fabio','golden retriever');What sentence would the following statement produce?print "<p>The dog is a $dogs{'Sparky'}</p>";Solution: (try not to peek)The dog is a dalmation.
Chapter 4
If you want to assign a value to a variable in an ordinary or associative array, all you have to do is reference the variable as described above. Then, type an equal sign and the value you wish to assign.Ordinary Array
Suppose, for example, that you want to change the third value in the following array from 'Carl' to 'Craig.'
@students=('Al','Betty','Carl','Donna','Eric','Fran');
This is all it would take to accomplish that task:
$students[2]='Craig';
The line above is equivalent to the following statement (but a lot easier to type):
@students=('Al','Betty','Craig','Donna','Eric','Fran');
Exercise:
Using pencil and paper, write a command that would change 'Donna' in the array named @students to 'Doris' in the most efficient manner possible.
Solution: (try not to peek)
$students[3]='Doris';Associative ArrayNow, suppose you wanted to change the street address in the following array:
%location=('Name','Lisa Suecke','Street','2101 Cloverwood', 'City','Scott AFB','State','IL','Zip','62225');
To change the street address, here's all you would have to type:
$location{'Street'}='123 Oak Grove Ln';The line above would be equivalent to this statement (but far easier to type):%location=('Name','Lisa Suecke','Street','123 Oak Grove Ln', 'City','Scott AFB','State','IL','Zip','62225');
Exercise:
Using pencil and paper, write a command that would change 'Lisa Suecke' in the array named %location to 'Kay Slate' in the most efficient manner possible.
Solution: (try not to peek)
$location{'Name'}='Kay Slate';
Chapter 5
Sorting an ordinary array is fairly easy. Here's an example of how it works:@colors=('red','green','blue','yellow','white','black'); @colors=sort @colors;The second line above sorts the values in the ordinary array called @colors and then replaces the old array with the new, sorted version. This creates the same results as the following statement (albeit with a lot less effort):@colors=('black','blue','green','red','white','yellow');Exercise:Using pencil and paper, write a command that would sort the values in the following ordinary array:
@titles=('Water Music','Cold Mountain','Confederacy of Dunces','Poisonwood Bible');
Solution: (try not to peek)
@titles=sort @titles;
Chapter 6
In Perl, a loop is a procedure that is repeated over and over again until a certain condition is met. One of the most common uses of loops is to extract data from ordinary and associative arrays of indeterminate length or origin.The type of loop that is most commonly used to perform this procedure is known as a 'foreach' loop. The instructions for implementing such a loop vary depending on whether you're working with an ordinary array or an associative array.
foreach loop: Ordinary Array
Let's say you'd like to create a loop that prints the contents of an ordinary array named @students.
To accomplish this task, all you will need to do is type the command 'foreach' followed by a space.
Then, you will need to create a variable to temporarily hold each item in the array. You can name the variable anything you'd like, as long as the variable name starts with a $ sign. I usually use $i (the 'i' is short for 'item').
Next, you will need to type another space and the name of the ordinary array. The array name should be surrounded by parentheses.
Then, you simply issue one or more commands to indicate what you'd like to do to each item in the array. As your program circles through the loop, the variable named $i (or whatever you called it) will take on the value of each item in the array.
Suppose you are working with an array that looks like this:
@students=('Al','Betty','Carl','Donna','Eric','Fran');
The first time through your foreach loop, the value of $i would be 'Al.' The second time through the loop, the value of $i would be 'Betty.' The next time through the loop, $i would be 'Carl,' and so on.
Here's an example of a complete Perl script that uses a foreach loop to pick apart an ordinary array:
#!/usr/local/bin/perl @students=('Al','Betty','Carl','Donna','Eric','Fran'); print "Content-type:text/html\n\n"; print "<HTML><BODY>"; foreach $i (@students) { print "<P>$i</P>"; } print "</BODY></HTML>";Notice how the line that begins with 'foreach' is not followed by a semicolon. In an earlier lesson, you learned that a semicolon is not required at the end of a comment line. Semicolons are also not required at the end of a line that is followed by an open curly bracket ({). All other command lines must end with a semicolon.The program above would create a web page that looks just like this:
Exercise:
Al Betty Carl Donna Eric Fran
Using pencil and paper, write a Perl script that creates an ordinary array named @colors containing the following values:
orange purple red yellow whiteIn the same script, write a foreach loop that will extract and print each value in the array to a web page.Solution: (try not to peek)
#!/usr/local/bin/perl @colors=('orange','purple','red','yellow','white'); print "Content-type:text/html\n\n"; print "<HTML><BODY>"; foreach $i (@colors) { print "<P>$i</P>"; } print "</BODY></HTML>";foreach loop: Associative ArrayLet's say you'd like to create a loop that prints the contents of an associative array named %inventory.
To accomplish this task, all you will need to do is type the command 'foreach' followed by a space.
Then, you will need to create a variable to temporarily hold the keys for each item in the array. You can name the variable anything you'd like, as long as the variable name starts with a $ sign. I usually use $i (the 'i' is short for 'item').
Next, you will need to type another space and, in parentheses, the word 'keys' followed by a space and the name of the associative array. Remember, the word 'key' is a synonym for the names we associate with the items in an associative array. Inserting the word 'keys' ensures that your program proceeds through the loop once only for each key in the array, and not for every single item in the array.
Once you have the foreach statement set up, you simply issue one or more commands to indicate what you'd like to do with each key in the array. As your program circles through the loop, the variable named $i (or whatever you called it) will take on the value of each key in the array.
Suppose you are working with an array that looks like this:
%inventory=('Rakes','42','Shovels','5','Hoes','27',);Because this associative array has three keys ('Rakes,' 'Shovels,' and 'Hoes'), your program will proceed through a foreach loop three times.The first time through your foreach loop, the value of $i would be 'Rakes.' The second time through the loop, the value of $i would be 'Shovels.' The final time through the loop, $i would be 'Hoes.'
As I mentioned earlier in this lesson, you can extract the values from this array by referring to them as follows:
$inventory{'Rakes'} $inventory{'Shovels'} $inventory{'Hoes'}As your program progresses through a foreach loop, $i will alternately take on the key value 'Rakes' and then 'Shovels' and then 'Hoes.' Therefore, the variable $inventory{$i} would be equivalent to $inventory{'Rakes'} the first time through the loop. The second time through the loop, $inventory{$i} would be the same as $inventory{'Shovels'}. We would see $inventory{$i} set to $inventory{'Hoes'} in the final lap through the loop.IMPORTANT: Notice how the variable $i is not surrounded with single quotes inside of the curly brackets. You must not surround a variable with single quotes--the single quotes should only be used when you are inserting the name of a key between the curly brackets.
Here's an example of a complete Perl program containing an associative array being picked apart by a foreach loop:
#!/usr/local/bin/perl %inventory=('Rakes','42','Shovels','5','Hoes','27',); print "Content-type:text/html\n\n"; print "<HTML><BODY>"; foreach $i (keys %inventory) { print "<P>The number of $i is $inventory{$i}</P>"; } print "</BODY></HTML>";The program above would create a web page that looks just like this:Exercise:
The number of Rakes is 42 The number of Shovels is 5 The number of Hoes is 27
Using pencil and paper, write a Perl script that would create the following associative array:
%employees=('David Bates','chef','Neal Kling','busboy','Warren Gold','waiter','Greg Rosicky','Manager');
In the same script, write a foreach loop that will extract and print each value in the associative array to a web page.
Solution: (try not to peek)
#!/usr/local/bin/perl %employees=('David Bates','chef', 'Neal Kling','busboy', 'Warren Gold','waiter', 'Greg Rosicky','Manager'); print "Content-type:text/html\n\n"; print "<HTML><BODY>"; foreach $i (keys %employees) { print "<P>The person named $i is our $employees{$i}</P>"; } print "</BODY></HTML>";
Chapter 7
-Quiz 6-This lesson has no quiz.
-Assignment E-
Write a new Perl script named 'test2.cgi'. In this script, create an associative array named '%in' (without the quotes). This array should have four keys named 'qty', 'size', 'color', and 'material'. The values of these keys should be:
quantity 2 size XL color blue material cottonWhen you finish setting up the array, write a foreach loop that will extract the value of each item in the array and writes the following lines on a web page:Order Summary: quantity: 2 size: XL color: blue material: cottonUse the instructions from part 2 of lesson 5 to log into your server, climb into the cgi-bin directory, upload your finished test2.cgi file, and set the file permissions (use rwx-rx-rx) again. Then, start your browser and test your program. If you get an error message, please consult the troubleshooting section in the last chapter of lesson 5. If you get stuck, a sample program that would satisfy the conditions of this assignment is listed below. Try not to look at the solution, if possible. You'll get much more experience if you write and debug your own program than if you just copy and paste my code into your text editor.Note: do not be surprised if the order of the values in your array changes when your web page prints (i.e., size before quantity, material before color, etc.). The Perl interpreter may change the order of the values in your associative array to permit a faster search time. In our next lesson, you will learn how to format the output to show the values in any order you desire.
Solution:
Here are a couple possible solutions to the problem:
Solution One:
#!/usr/local/bin/perl %in=('quantity','2','size','XL','color','blue','material','cotton'); print "Content-type:text/html\n\n"; print "<HTML><BODY>"; print "<p><b>Order Summary</b></p>"; foreach $i (keys %in) { print "<P>$i: $in{$i}</P>"; } print "</BODY></HTML>"; #end of programSolution Two:Here's a solution that uses the PrintTag trick to generate some of the HTML. Please make sure there are no spaces or tabs between the print <<"PrintTag"; statement and the initial <HTML> tag. Also, be sure to press the ENTER key at least once after the very last PrintTag line:
#!/usr/local/bin/perl %in=('quantity','2','size','XL','color','blue','material','cotton'); print "Content-type:text/html\n\n"; print <<"PrintTag"; <HTML><BODY> <p><b>Order Summary</b></p> PrintTag foreach $i (keys %in) { print "<P>$i: $in{$i}</P>"; } print <<"PrintTag"; </BODY></HTML> PrintTag #end of programSolution Three:This solution uses a table for a more orderly arrangement:
#!/usr/local/bin/perl %in=('quantity','2','size','XL','color','blue','material','cotton'); print "Content-type:text/html\n\n"; print "<HTML><BODY>"; print "<TABLE BORDER=\"1\">"; print "<TR><TH colspan=\"2\">Order Summary</TH></TR>"; foreach $i (keys %in) { print "<TR><TD>$i:</TD><TD>$in{$i}</TD></TR>"; } print "</TABLE>"; print "</BODY></HTML>";
IMPORTANT: This version of your lesson is for saving or printing only. All links and images have been disabled to decrease download time and help you avoid printer difficulties. Do NOT attempt to click any of the links on this page.
Copyright 1999 by ed2go.com. All rights reserved.
No reproduction or redistribution without written
permission.