Post on 19-Dec-2015
2*Copyright © 2002 Pearson Education, Inc.
Web Wizard’s Guide to CGI/Perl
David Lash
Chapter 3
Perl Basics
3*Copyright © 2002 Pearson Education, Inc.
Chapter Objectives
Describe Perl scalar variables for numerical and string data
Describe Arithmetic Operations Describe Perl conditional statements
4*Copyright © 2002 Pearson Education, Inc.
Using Scalar Variables
Variables allow you to store and access data in computer memory.
Two primary types: » Scalar variables - hold a singular item such
as a number (for example, 1, 1239.12, or –123) or a character string (for example, “apple,” “ John Smith,” or “address”).
» List variables - hold a set of items (such as a set of numbers). (More in Chapter 5).
5*Copyright © 2002 Pearson Education, Inc.
Assigning Values to Variables
Place the variable’s name on the left side of an equals sign (=) and the value on the right side of the equals sign.
The following Perl statements use two variables: $x and $months
$x = 3; $months = 12;
Name of variable. Variable's new value
6*Copyright © 2002 Pearson Education, Inc.
$X = 60; $Weeks = 4; $X = $Weeks;
Assigns 4 to $X and $Weeks. Note: Perl variables are case sensitive.
» $x and $X are considered different variable names.
Assigning New Values to Variables
7*Copyright © 2002 Pearson Education, Inc.
Selecting Variable Names
Perl variable rules
» Perl variable names must have a dollar sign ($) as the first character.
» The second character must be a letter or underscore (_).
» Less than 251 characters.» Valid: $baseball, $_sum, $X, $Numb_of_bricks, $num_houses, and $counter1.
» Not Valid: $123go, $1counter, and counter.
8*Copyright © 2002 Pearson Education, Inc.
Variables and the print Place a variable name inside the double quotes of the print statement. to print out the value. E.g.,
» print “The value of x= $x”;
1. #!/usr/bin/perl2. print “Content-type: text/html\n\n”;3. $x = 3;4. $y = 5;5. print “The value of x is $x. ”;6. print “The value of y= $y.”;
Assign 3 to $x
Assign 5 to $x
10*Copyright © 2002 Pearson Education, Inc.
Operating on Variables
Perl expressions are used to manipulate data values. » Use operators such as a plus sign (+) for addition and a
minus sign (–) for subtraction. For example, 1. #!/usr/bin/perl2. print “Content-type: text/html\n\n”;3. $x = 3 + 4; 4. $y = 5 + $x; 5. print “The value of x is $x but y = $y”;
Assign 7 to $xAssign 12 to $y
12*Copyright © 2002 Pearson Education, Inc.
Some Key Perl Operators
Operator Effect Example Result
+ Adds two
items
$x = 2 + 2; $x is assigned 4
- Subtraction $y = 3; $y = $y – 1; $y is assigned 2
/ Division $y = 14 / 2; $y is assigned 7
* Multiplication $z = 4; $y = $z * 4; $y is assigned 16
** Exponent $y = 2; $z = 4 ** $y;
$z is assign 16
% Remainder $y = 14 % 3; $y is assigned 2
13*Copyright © 2002 Pearson Education, Inc.
Example Program
1. #!/usr/bin/perl2. print “Content-type: text/html\n\n”;3. $cubed = 3 ** 3; 4. $onemore = $cubed + 1;5. $cubed = $cubed + $onemore;6. $remain = $onemore % 3;7. print “The value of cubed is $cubed onemore= $onemore ”;
8. print “The value of remain= $remain”;
Assign 27 to $cubedAssign 55 to $cubed
$remain is remainder of 28 / 3 or 1
15*Copyright © 2002 Pearson Education, Inc.
Writing Complex Expressions
Operator precedence rules define the order in which the operators are evaluated.
For example, consider the following expression:
» $x = 5 + 2 * 6; » $x could = 56 or 17 depending on evaluation
order
16*Copyright © 2002 Pearson Education, Inc.
Perl Precedence Rules
1. Operators within parentheses.
2. Exponential operators.
3. Multiplication and division operators.
4. Addition and subtraction operators.
Evaluates to 82
Evaluates to 19
Consider the following$X = 100 – 3 ** 2 * 2; $Y = 100 – ((3 ** 2) * 2);$Z = 100 – ( 3 ** (2 * 2) );
17*Copyright © 2002 Pearson Education, Inc.
Variables with HTML Output - II
1. #!/usr/bin/perl
2. print “Content-type: text/html\n\n”;
3. print “<HTML> <HEAD> <TITLE> Example </TITLE></HEAD>”;
4. print “<BODY> <FONT COLOR=BLUE SIZE=5>”;
5. $num_week = 8;
6. $total_day = $num_week * 7;
7. $num_months = $num_week / 4;
8. print “Number of days are $total_day </FONT>”;
9. print “<HR>The total number of months=$num_months”;
10. print “</BODY></HTML>”;
Assign 28Assign 2
Set bluefont, size 5
Horizontalrule followed by black font.
19*Copyright © 2002 Pearson Education, Inc.
String Variables
Variables can hold numerical or character string data» For example, to hold customer names,
addresses, product names, and descriptions. $letters=”abc”;
$fruit=”apple”;
Assign “abc”
Assign “apple”
Enclose in double quotes
20*Copyright © 2002 Pearson Education, Inc.
String Variables String variables have their own operations.
» You cannot add, subtract, divide, or multiply string variables.
The concatenate operator joins two strings together and takes the form of a period (“.”).
The repeat operator is used when you want to repeat a string a specified number of times.
21*Copyright © 2002 Pearson Education, Inc.
Concatentate Operator
Joins two strings together (Uses period (“.”)).
$FirstName = “Bull”;$LastName = “and Bear”;$FullName1 = $FirstName . $LastName;$FullName2 = $FirstName . “ “ . $LastName;
print “FullName1=$FullName1 and
Fullname2=$FullName2”;
Would output the following:
FullName1=Bulland Bear and FullName2=Bull and Bear
22*Copyright © 2002 Pearson Education, Inc.
Repeat Operator Used to repeat a string a number of times. Specified by the
following sequence:
$varname x 3
For example,
$score = “Goal!”;$lots_of_scores = $score x 3;print “lots_of_scores=$lots_of_scores”;
Would output the following:
lots_of_scores=Goal!Goal!Goal!
Repeat string value3 times.
23*Copyright © 2002 Pearson Education, Inc.
Repeat W/o Repeat Operator You don’t have to use the repeat operator. Also common to see …
For example,
$score = “Goal!”;$lots_of_scores = “$score$score$score”print “lots_of_scores=$lots_of_scores”;
Would output the following:
lots_of_scores=Goal!Goal!Goal!
Repeat string value3 times.
24*Copyright © 2002 Pearson Education, Inc.
A Full Program Example Using Repeat Operator ...
1. #!/usr/bin/perl2. print "Content-type: text/html\n\n";3. print "<HTML> <HEAD><TITLE> String Example</TITLE></HEAD>";
4. print "<BODY>";5. $first = "John";6. $last = "Smith";7. $name = $first . $last;8. $triple = $name x 3;9. print "<BR> name=$name";10.print "<BR> triple = $triple";
11. print "</BODY></HTML>";
Concatenate
Repeat
26*Copyright © 2002 Pearson Education, Inc.
Conditional Statements
Conditional statements enable programs to test for certain variable values and then react differently
Use conditionals in real life: » Get on Interstate 90 East at Elm Street and go east toward the city. If you encounter construction delays at mile marker 10, get off the expressway at this exit and take Roosevelt Road all the way into the city. Otherwise, stay on I-90 until you reach the city.
27*Copyright © 2002 Pearson Education, Inc.
Conditional Statements Perl supports 3 conditional clauses:
» An if statement specifies a test condition and set of statements to execute when a test condition is true.
» An elsif clause is used with an if statement and specifies an additional test condition to check when the previous test conditions are false.
» An else clause is used with an if statement and possibly an elsif clause. It specifies a set of statements to execute when one or more test conditions are false.
28*Copyright © 2002 Pearson Education, Inc.
The if Statement Uses a test condition and set of statements to
execute when the test condition is true.
» A test condition uses a test expression enclosed in parentheses within an if statement.
» When the test expression evaluates to true, then one or more additional statements within the required curly brackets ({ … }) are executed.
if ( $aver > 69 ) { $Grade="Pass"; print "Grade=$Grade";}print "Your average was $aver";
Statement(s) to executeregardless of test condition.
Execute these statementswhen $aver is greater than 69.
29*Copyright © 2002 Pearson Education, Inc.
Numerical Test Operators
Numerical Test Operator
Effect Example Result
== Equal to if ($x == 6){ $x = $y + 1; $y = $x + 1; }
Execute the second and third statements if the value of $x is equal to 6.
!= Not equal to if ($x != $y) { $x = 5 + 1; }
Execute the second statement if the value of $x is not equal to the value of $y.
< Less than if ($x < 100) { $y = 5; }
Execute the second statement if the value of $x is less than 100.
> Greater than if ($x > 51) { print “OK”; }
Execute the second statement if the value of $x is greater than 51.
>= Greater than or equal if (16 >= $x) {
print “x=$x”; }
Execute the second statement if 16 is greater than or equal to the value of $x.
>= Greater than or equal if (16 >= $x) {
print “x=$x”; }
Execute the second statement if 16 is greater than or equal to the value of $x.
30*Copyright © 2002 Pearson Education, Inc.
A Sample Conditional Program
1. #!/usr/bin/perl2. print "Content-type: text/html\n\n";3. print "<HTML> <HEAD><TITLE> String Example </TITLE></HEAD>";
4. print "<BODY>";5. $grade = 92; 6. if ( $grade > 89 ) { 7. print “<FONT COLOR=BLUE> Hey you got an A.</FONT><BR> ”; 8. } 9. print “Your actual score was $grade”;
10. print “</BODY></HTML>”;
32*Copyright © 2002 Pearson Education, Inc.
Different Values of Line 5
Line 5 Output
$grade=92;
Hey you got an A.
Your actual score was 92
$grade=89;
Your actual score was 89
$grade=40;
Your actual score was 40
$grade=1100;
Hey you got an A.
Your actual score was 1100
$grade=-50;
Your actual score was –50
1. #!/usr/bin/perl2. print "Content-type: text/html\n\n";3. print "<HTML> <HEAD><TITLE> String Example
</TITLE></HEAD>";4. print "<BODY>";5. $grade = 92; 6. if ( $grade > 89 ) { 7. print “<FONT COLOR=BLUE> Hey you got an A.</FONT><BR> ”; 8. } 9. print “Your actual score was $grade”;
10. print “</BODY></HTML>”;
33*Copyright © 2002 Pearson Education, Inc.
String Test Operators Perl supports a set of string test operators that are based
on ASCII code values.
» Standard, numerical representation of characters.
» Every letter, number, and symbol translates into a code number.
– “A” is ASCII code 65, and “a” is ASCII code 97.
– Numbers are lower ASCII code values than letters, uppercase letters lower than lowercase letters.
– Letters and numbers are coded in order, so that the character “a” is less than “b”, “C” is less than “D”, and “1” is less than “9”.
34*Copyright © 2002 Pearson Education, Inc.
String Test OperatorsTest Operator Effect Example Result
eq Equal to $name=”Nelson”; if ($name eq “Nelson”){ print “Got Nelson”; }
Prints Got Nelson because $name is equal to “Nelson”.
ne Not equal to $alert=”Smoke”; if ( $alert ne “fire” ){ print “$alert NE fire”; $ok = $ok + 1; }
Prints Smoke NE fire and then executes fourth line, because $alert is not equal to “fire”.
lt Less than if ( “auto” lt “car” ) { print “Before car”; }
Prints Before car because “auto” is less than “car”.
gt Greater than if (“Jones” gt “Smith” ){ print “After Smith”; }
Prints nothing because “Jones” is not greater than “Smith”.
ge Greater than or equal to
if ( “WSOX” ge “Cubs” ){ print “Sox Win”; }
Prints Sox Win because “WSOX” is greater than or equal to “Cubs”.
le Less than or equal to $Name = “Bob”; if (“Bob” le $Name ) { print “Got Bob”; }
Prints Got Bob because “Bob” is less than or equal to $Name.
35*Copyright © 2002 Pearson Education, Inc.
The elsif Clause
Specifies an additional test condition to check when all previous test conditions are false. » Used only with if statement» When its condition is true, gives one or more
statements to execute $found = 0; if ( $name eq "Joe" ) {
print "Got Name of Joe";$found = 1;
} elsif ( $name eq "Jane" ) {
print "Got Name of Jane";$found = 1;
} print "Name=$name and found=$found\n";
Execute these whenif condition is true.
Execute these whenits condition is true
but previous is false.
Executetregardless of theprevioustest conditions.
36*Copyright © 2002 Pearson Education, Inc.
The elsif Clause 1. #!/usr/bin/perl2. print “Content-type: text/html\n\n”;3.$grade = 92; 4.if ( $grade > 100 ) { 5. print “Illegal Grade > 100”;6.} 7.elsif ( $grade > 89 ){ 8. print “Hey you got an A ”; 9.}
1.0 print “Your actual grade was $grade”;
Line 3 Output
$grade=92; Hey you got an A Your actual grade was 92
$grade=89; Your actual grade was 89
$grade=40; Your actual grade was 40
$grade=1100; Illegal Grade > 100 Your actual grade was 1100
$grade=-50; Your actual grade was –50
37*Copyright © 2002 Pearson Education, Inc.
The elsif Clause
1. #!/usr/bin/perl2.print “Content-type: text/html\n\n”;3.$grade = 92; 4.if ( $grade >= 100 ) { 5. print “Illegal Grade > 100 ”;6.}7.elsif ( $grade < 0 ) { 8. print “illegal grade < 0 ”; 9.} 10.elsif ( $grade > 89 ){ 11. print “Hey you got an A ”; 12.}
13. print “Your actual grade was $grade”;
38*Copyright © 2002 Pearson Education, Inc.
Some Sample Values for Line 3
Line 3 Output
$grade=92; Hey you got an A Your actual grade was 9
$grade=89; Your actual grade was 89
$grade=40; Your actual grade was 40
$grade=1100; Illegal Grade > 100 Your actual grade was 1100
$grade=-50; illegal grade < 0 Your actual grade was –50
1. #!/usr/bin/perl2.print “Content-type: text/html\n\n”;3.$grade = 92; 4.if ( $grade >= 100 ) { 5. print “Illegal Grade > 100 ”;6.}7.elsif ( $grade < 0 ) { 8. print “illegal grade < 0 ”; 9.} 10.elsif ( $grade > 89 ){ 11. print “Hey you got an A ”; 12.}
13. print “Your actual grade was $grade”;
39*Copyright © 2002 Pearson Education, Inc.
The else Clause
Specifies a set of statements to execute when all other test conditions in an if block are false.
» It must be used with at least one if statement, (can also be used with an if followed by one or several elsif statements.
if ( $name eq "Joe" ) {print "Got Name of Joe";
} elsif ( $name eq "Jane" ) {
print "Got Name of Jane"; } else {
print "Could not validate Name=$name"; }
One or more statements to executewhen test condition is true.
One or more statements to executewhen its test condition is true but the previous testcondition is false.
One or more statements to executewhen the previous test condition(s) are false.
40*Copyright © 2002 Pearson Education, Inc.
Using An Else Clause
1.#!/usr/bin/perl2.print “Content-type: text/html\n\n”;3.$grade = 92; 4.if ( $grade >= 100 ) {5. print “Illegal Grade > 100”;6.}7.elsif ( $grade < 0 ) { 8. print “illegal grade < 0”; 9.} 10.elsif ( $grade > 89 ){ 11. print “Hey you got an A”; 12.} 13.else { 14. print “Sorry you did not get an A”;
15.}
41*Copyright © 2002 Pearson Education, Inc.
Sample Values of Line 3
Line 3 Output
$grade=92; Hey you got an A
$grade=89; Sorry you did not get an A
$grade=40; Sorry you did not get an A
$grade=1100; Illegal Grade > 100
$grade=-50; illegal grade < 0 1.#!/usr/bin/perl2.print “Content-type: text/html\n\n”;3.$grade = 92; 4.if ( $grade >= 100 ) {5. print “Illegal Grade > 100”;6.}7.elsif ( $grade < 0 ) { 8. print “illegal grade < 0”; 9.} 10.elsif ( $grade > 89 ){ 11. print “Hey you got an A”; 12.} 13.else { 14. print “Sorry you did not get an A”;
15.}
42*Copyright © 2002 Pearson Education, Inc.
Summary Variables are used to store and access data in
computer memory. Numerical and string variables have unique
operations that can be used to manipulate their values.
Conditional statements are used to test for conditions and, based on the results of the test, execute specific program statements. Perl provides different test condition operators for string and numerical variables.
43*Copyright © 2002 Pearson Education, Inc.
Summary The if statement can be used by itself
and is a basic way of testing conditions. The elsif clause can be used with the if statement to provide another test condition when the original if statement is false. An else clause provides statements that execute when all other if and elsif conditions are false.
44*Copyright © 2002 Pearson Education, Inc.
Perl “Jeoprdy”
Answer: $1st_counter, $2ndctr, squared?
Question: Give an example of 3 illegal variable names.
Question: What are the Perl operator precedence order?
Answer: exponential operators, parenthesis, multiplication & division, addition & subtraction
45*Copyright © 2002 Pearson Education, Inc.
So think your smart? Answer: (a) if, elsif, else (b) if
Question: Which three types of conditional clauses were described in this chapter. Which is the only one that can be used by itself?
Question: Which test operator is used to test whether one of two string variables is greater than the other? What test operator is used to test whether one of two numerical variables is greater than the other?
Answer: gt, >