Lesson 3 -- 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
The word 'variable' means 'something that can change.' In the world of Perl programming, a variable is simply a name we attach to one or more changeable values that we want to remember.The values we want to remember could be:
-words, such as the names of people who visit our website, or the cities and states where our visitors hail from. Programmers do not refer to words as 'words,' however. Programmers refer to a word or a phrase or a sentence or a paragraph or any other combination of letters, numbers, spaces and punctuation marks as a 'string.' A variable that contains a string is known as a 'string variable.'
-numbers, such as the number of products a customer wishes to purchase from an online store, the prices of these products, or the sales tax and shipping rates to be billed to the customer. A variable that contains a number is known as a 'numeric variable.'
In Perl, a variable can have any name you want to give it. That name must start with a $ sign, followed by as many letters and numbers as you will need. The name should not contain any spaces, and it is case-sensitive. A variable named $shipping would not be considered the same as a variable named $Shipping or $SHIPPING.
In the real world, variables are often used as conversational shortcuts. It is far easier (and a lot less embarrassing) to say talk about your "car" than it is to talk about your "green and white 1976 AMC Pacer." And it takes a lot less effort to casually refer to your "house" instead of "the third apartment from the elevator on the left side of the hallway on the fifteenth floor of the building at 1852 18th Street."
The word "car" and the word "home" are both variables. Those two monosyllabic words are quick and excellent conversational stand-ins for the specific vehicle we are currently driving or the location of our current residence. If you trade in your aging Pacer for something with a bit more zing, you'll still call the new vehicle your "car." If you pack up your belongings and take up digs across town, you'll still call your new digs your "home."
You can also use variables as a form of shorthand in your Perl programs. Suppose you are selling a product that costs 31,274.95 dollars to other businesses over the web. Suppose further that your program has to perform a variety of calculations on that number.
Assuming that you will need to type this value repeatedly, wouldn't it be easier to use the name "$price" as a stand-in for the number 31274.95? This would allow us to quickly substitute "$price" each time we would ordinarily have had to type the number 31274.95.
Using the variable in our program instead of the actual number will help us in a variety of ways:
-first of all, $price is easier to remember than 31274.95. We should be able to type $price from memory. Typing the actual number from memory would be a tad bit more difficult.
-the chances of making a typographical error are greater if we are forced to type the actual value than if we type the variable name. If we transposed two of the digits in 31247.95, it wouldn't be as easy to spot the error than if we were to transpose two of the letters in $priec. Ask yourself: did you spot two typographical errors in the last sentence? If you did, which one jumped out at you...and which one required a bit of double-checking?
-and finally, if the price for our product were to be changed, wouldn't it be a lot easier to just assign a new value to the variable named $price than to pore over our program, carefully changing each and every 31274.95 that pops up in our program to some new value?
I am sure you will agree that the arguments for using variables to represent values are persuasive. However, one question yet remains--how do we assign a value to a variable?
Although you could assign values to your variables at any time and on any line of your program, it is best to define all of your variables right up front. We call this practice 'initializing the variables.'
Initializing your variables serves two important purposes:
1. the practice makes your program easier to understand.
The plot of a finely crafted novel is much easier to follow if we are introduced to the cast of characters early in the story. Although it is within their power to create characters out of thin air whenever and wherever they want, a skilled novelist would never even consider unexpectedly injecting a new major character into the middle or end of a story. Such an action would confuse and distract the reader.
Likewise, it will be a lot easier for you and your co- workers to understand your program if you take care to introduce all of your variables as soon as possible.
2. the practice makes your programs easier to modify.
If you ever need to change the value that has been assigned to one or more variables, it will be a lot easier for you to do so if all the variables are grouped together at the beginning of your program. Locating and changing the value assigned to a variable becomes exponentially more difficult if the variable is tucked randomly deep inside your code.
Chapter 2
Assigning a value to a variable is quite simple. All you have to do is type the name you'd like to give the variable, followed by an equal sign (=) and the value you'd like to assign to the variable. As I mentioned in our last lesson, this and all other non- comment lines should end with a semicolon (;).The name of the variable can contain numbers or letters, but it cannot contain spaces and most punctuation marks. It must also start with a $ sign.
The value after the = sign can be a string or a number. If the value is a number, you can just type the number. If the value is a string, you must surround the string with quote marks ("). The string can contain spaces.
Here are a couple of examples:
$quantity=12; $CatchPhrase="yada yada yada";Notice how I used a couple of capital letters in the name of the second variable above. Because I cannot use spaces in a variable name, I used the upper case letters to make the two words in the variable name easier to read. However, because variable names are case-sensitive, I must remember to always type the variable name exactly as I typed it above.What if you want to assign a string that contains a quote mark to a variable? As I mentioned in lesson 2, the Perl interpreter doesn't like to see more than two quotes on the same line. If the string itself contains a quote mark ("), you must precede the quote mark by a backslash. The backslash tells the interpreter not to take the character that follows literally.
For example, suppose you want to assign the string value on the line below to a variable named $castaway
Bob "Gilligan" Denver
Because the Perl interpreter can't handle more than one pair of quotes on any one line (unless they are preceded by a backslash), we would need to type:
$castaway="Bob \"Gilligan\" Denver";-Mathematical Operators-Perl makes it easy to do math with your numeric variables. If you've ever worked with a spreadsheet application (such as Lotus 1-2-3 or Microsoft Excel), you'll probably be familiar with the mathematical operators you can use:
+ add
- subtract
* multiply
/ divide
** exponentiate
When writing mathematical equations, it is considered a good programming practice to use only variables and mathematical operators in those equations. Any equation that contains an actual number indicates poor program design.
Why? Well, let me illustrate with an example:
Please tell me what each of the three values to the right of the equal sign is supposed to represent:
$total=.48*45+17.55;Difficult to answer that question, isn't it? Let's try again, with a similar equation. But first, let me initialize three variables.$price=.48; $quantity=45; $shippingCost=17.55; $total=0;Again, all you have to do is tell me what each of the three values to the right of the equal sign is supposed to represent:$total=$price*$quantity+$shippingCost;I am sure that you will agree it was a lot easier for you to answer my question when I used variables to stand for the numbers in the equation.Think about this little exercise the next time you write a program in Perl. Using variables to represent the numbers in an equation will make the equation much easier for you and your coworkers to understand. That sort of readability will prove to be very important if the program ever needs to be modified in the future.
-Order of Operations-
In a Perl program, mathematical operations always take place in a certain order. This order is outlined below:
First priority: (anything in parentheses)
Second priority: exponentiation
Third priority: multiplication and division
Fourth priority: addition and subtraction
If, when writing your CGI programs, you create a complex equation that contains a mixture of addition, subtraction, multiplication, division, and/or exponentiation, the equation will be processed in the order described above.
Once again, allow me to illustrate this concept with some examples:
$total=$price*$quantity+$shippingCost;In the equation above, $price will be multiplied with $quantity first. $shippingCost will be added to the product obtained by multiplying those two numbers. This is because multiplication takes precedence over addition.$average=($quizScore1+$quizScore2)/$numberOfQuizzes;Even though division would ordinarily take place before addition, I have changed the balance of power by surrounding the addition part of the equation with parentheses. According to the rules, anything surrounded by parentheses will be given the highest priority.Therefore, in this equation, $quizScore1 will be added to quizScore2 before being divided by $numberOfQuizzes.
Chapter 3
Once you have assigned a value to a variable, you can refer to that variable in your HTML. The Perl interpreter will not simply echo back the variable's name when it produces your web page. Instead, it will substitute the value of that variable for the variable's name. This process is known as interpolation.Suppose, for example, you had assigned a value of 100 to a variable named $quantity. If one of the lines in your program looked like this:
print "You ordered $quantity units of our product.";The Perl interpreter would substitute 100 for $quantity, producing the following line of text on your screen:You ordered 100 units of our product.
Note: If you ever need to display a $ sign on your web page, be sure and precede it with a backslash (\). If you fail to do so, the Perl interpreter will think the $ sign is the beginning of another variable and it will try to interpolate. The backslash tells the Perl interpreter that the $ sign is just a $ sign and it should not be taken literally.
-Sample Program-
Here's an example of a complete Perl program that uses variables. Notice the backslash in front of the $ sign on the last line of our HTML file.
#!/usr/bin/perl #Line above gives path to Perl interpreter $price=9; $quantity=25; $total=0; $description="Universal remote controls"; #Lines above initialize variables print "Content-type: text/html\n\n"; #Line above warns browser that HTML is coming $total=$price*$quantity; #Line above calculates total purchase price #Lines below produce HTML page print <<"PrintTag"; <html><head> <title>Order Confirmation</title> </head><body> <P>You ordered $quantity $description today.</P> <P>That's going to set you back \$ $total.</P> </body></html> PrintTag #End of programIf we were to run this program, it would produce a web page containing the following two statements:You ordered 25 Universal remote controls today.
That's going to set you back $ 225.
Chapter 4
-Quiz 3-When you feel you have a grasp on all of the concepts taught within this lesson, I would like you to take a short, multiple choice quiz. To get to the quiz, click on 'Quizzes' on the menu bar. When the form comes up, input your last name, e-mail address, and password, and make sure you have 'Quiz 3' selected. Good luck!
-Assignment B-Create a Perl program with the following three numeric variables:
$FeetPerMile $Feet $MilesAssign a value of 5280 to the variable named $FeetPerMile. Assign an initial value of 0 to the variable named $Feet. Assign any value you want to the variable named $Miles.Have your program perform a calculation that will determine the value of $Feet by multiplying $Miles by $FeetPerMile.
Then, have your program produce a web page to display the calculated value of $Feet. This assignment is to be completed on your own. A possible solution appears below (try not to peek until you've written your program), so there is no need to send me anything. Please post a question in the discussion area if you have any problems.
Possible Assignment Solution
This is just one solution. Your program may differ slightly.#!/usr/bin/perl $Miles=5; $FeetPerMile=5280; $Feet=0; print "Content-type: text/html\n\n"; $Feet=$Miles*$FeetPerMile; print <<"PrintTag"; <html><head> <title>Results of Calculation</title> </head><body> <P>There are $Feet feet in $Miles miles.</P> </body></html> PrintTag #End of program
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.