Introduction to Programming the WWW I CMSC 10100-1 Winter 2004 Lecture 7.

56
Introduction to Programming the WWW I CMSC 10100-1 Winter 2004 Lecture 7

description

3 Reminder Hw1 & hw2 grade Hw3 due this Friday midnight Midterm next week (50min)  Will give some outline next class

Transcript of Introduction to Programming the WWW I CMSC 10100-1 Winter 2004 Lecture 7.

Page 1: Introduction to Programming the WWW I CMSC 10100-1 Winter 2004 Lecture 7.

Introduction to Programming the WWW ICMSC 10100-1

Winter 2004Lecture 7

Page 2: Introduction to Programming the WWW I CMSC 10100-1 Winter 2004 Lecture 7.

2

Today’s Topics

• CSS (cont’d)• Common Gateway Interface (CGI)• Review of introduction to perl• Perl data types and variables

Page 3: Introduction to Programming the WWW I CMSC 10100-1 Winter 2004 Lecture 7.

3

Reminder

• Hw1 & hw2 grade• Hw3 due this Friday midnight• Midterm next week (50min)

Will give some outline next class

Page 4: Introduction to Programming the WWW I CMSC 10100-1 Winter 2004 Lecture 7.

4

The Common Gateway Interface (CGI)

• A standard that enables Web browsers to exchange data with computer programs located on a Web server

• First appeared in the NCSA HTTPD Web server software built by the National Center for Super-computing Applications (NCSA) One of the first widely used Web servers Was simple and the program source code was made available

for free • It is simple to use and available on a variety of Web

servers

Page 5: Introduction to Programming the WWW I CMSC 10100-1 Winter 2004 Lecture 7.

5

How Browsers and Web Application Work with CGI

1. Server delivers blank form to web browser

2. User fills in form and browser returns fill-in data to server

3. Web server spawns a process to run the user's CGI script which:

a. processes the data the user fills in

b. passes mail message to mail system

c. passes html back to web server

4. Web server returns html generated by program to web browser

Page 6: Introduction to Programming the WWW I CMSC 10100-1 Winter 2004 Lecture 7.

6

An Interface with Different Programming Languages

• Web application programs that are developed specifically to work with the CGI standard are known as CGI programs

• Lots of different programming languages can be used. For example, Perl, Visual Basic, Java, C, C++, UNIX shell scripts, etc

Page 7: Introduction to Programming the WWW I CMSC 10100-1 Winter 2004 Lecture 7.

7

CGI Program Use Cases

• Carries out many dynamic tasks, such as the following: Input a search term, search the WWW, and return the

results Calculate and display the number of times that a page

has been viewed Verify the input fields on a Web form Save a Web form into a database Display a special graph, or return the results of a

calculation based on data input from a form

Page 8: Introduction to Programming the WWW I CMSC 10100-1 Winter 2004 Lecture 7.

8

First Perl Script Running Over the Internet

• The first line should be a “pound-bang” line to make the script self-executable “#!” + full path to the location of perl interpreter

• add a MIME content-type line to run the script in a browser over the Internet

• A simple example:#!/usr/local/bin/perl print “Content-type: text/plain\n\n”;print “my 1st perl script\n”;

Page 9: Introduction to Programming the WWW I CMSC 10100-1 Winter 2004 Lecture 7.

9

Programming Language Components

• Data types Define what kinds of data Two primary data types in Perl: number and strings

• Operators An operator typically takes one or more data items and

produces a result Common operator types:

• Mathematical operators• String operators• Logical operators

• Variables Variables are temporary storage places for data

Page 10: Introduction to Programming the WWW I CMSC 10100-1 Winter 2004 Lecture 7.

10

Programming Language Components (cont’d)

• Reserved words a number of words that have a special meaning within

the language syntax• Data structures (advanced data types)

Collections of data that can be accessed in a certain way Can be defined by language (list, array, hash table, etc)

or by the programmer• Functions (subroutines)

Blocks of codes that perform certain programming tasks. Chunks of reusable code that can be 'called' by a

program when needed

Page 11: Introduction to Programming the WWW I CMSC 10100-1 Winter 2004 Lecture 7.

11

Perl Programming Language Structure

• A Perl program (script) consists of a sequence of declarations (optional) and statements Only report formats and functions need to be declared The sequence of statements is executed just once

• Statements and compound statements (statement blocks) A complete unit of execution Perl statements must end with a “;” A sequence of statements may be treated as one statement by

enclosing it in “{}”• Expressions and compound expressions

An expression is a series of variables, operators, and functions that are evaluated and result in single value

Expressions can be combined in compound expressions Statements are built upon expressions

Page 12: Introduction to Programming the WWW I CMSC 10100-1 Winter 2004 Lecture 7.

12

Perl Data Types

• Scalars The simplest kind of data Perl can work with Either a string or number (integer, real, etc)

• Arrays of scalars An ordered sequence of scalars

• Associate arrays of scalars (hash) A set of key/value pairs where the key is a

text string to help to access the value

Page 13: Introduction to Programming the WWW I CMSC 10100-1 Winter 2004 Lecture 7.

13

Using Variables

• Variables allow you to store and access data in computer memory

• Three variable 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”)

Array variables - hold a set of items (discuss later)

Hash variables – hold a set of key/value pairs

Page 14: Introduction to Programming the WWW I CMSC 10100-1 Winter 2004 Lecture 7.

14

Scalar Variable and Assignment• A scalar variable in Perl is always

preceeded by the $ sign• 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

Page 15: Introduction to Programming the WWW I CMSC 10100-1 Winter 2004 Lecture 7.

15

$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

Page 16: Introduction to Programming the WWW I CMSC 10100-1 Winter 2004 Lecture 7.

16

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.

Page 17: Introduction to Programming the WWW I CMSC 10100-1 Winter 2004 Lecture 7.

17

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 $xAssign 5 to $y

Page 18: Introduction to Programming the WWW I CMSC 10100-1 Winter 2004 Lecture 7.

18

Would Output The Following:

Page 19: Introduction to Programming the WWW I CMSC 10100-1 Winter 2004 Lecture 7.

19

Quotation Marks

• Double quotation marks (“ “) Allow variable interpolation and escape sequences

• Variable Interpolation: any variable within double quotes will be replaced by its value when the string is printed or assigned to another variable

• Escape Sequences: Special characters in Perl: “ ‘ # $ @ %

• Not treated as characters if included in double quotes• Can be turned to characters if preceeded by a \ (backslash)

Other backslash interpretations (Johnson pp. 62)• \n – new line \t – tab

• Double quotes examples

Page 20: Introduction to Programming the WWW I CMSC 10100-1 Winter 2004 Lecture 7.

20

Quotation Marks

• Single quotation marks (‘ ‘) Marks are strictest form of quotes Everything between single quotes will be

printed literally How to print a single quote (‘) inside of a

single quotation marks?• Use backslash preceeding it

Single quotes examples

Page 21: Introduction to Programming the WWW I CMSC 10100-1 Winter 2004 Lecture 7.

21

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

Page 22: Introduction to Programming the WWW I CMSC 10100-1 Winter 2004 Lecture 7.

22

String Variables

• The use of double quotes allows you to use other variables as part of the definition of a variable $my_stomach='full';$full_sentence="My stomach feels $my_stomach."; print "$full_sentence";

The value of $my_stomach is used as part of the $full_sentence variable

Page 23: Introduction to Programming the WWW I CMSC 10100-1 Winter 2004 Lecture 7.

23

Perl Operators

• Different versions of the operators for numbers and strings

• Categories: Arithmetic operators Assignment operators Increment/decrement operators concatenate operator and repeat operator Numeric comparison operators String comparison operators Logical operators

Page 24: Introduction to Programming the WWW I CMSC 10100-1 Winter 2004 Lecture 7.

24

Arithmetic OperatorsOperator 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

Page 25: Introduction to Programming the WWW I CMSC 10100-1 Winter 2004 Lecture 7.

25

Example Program1. #!/usr/local/bin/perl2. print “Content-type: text/plain\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

Page 26: Introduction to Programming the WWW I CMSC 10100-1 Winter 2004 Lecture 7.

26

Would Output The Following ...

Page 27: Introduction to Programming the WWW I CMSC 10100-1 Winter 2004 Lecture 7.

27

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 = 42 or 17 depending on evaluation

order

Page 28: Introduction to Programming the WWW I CMSC 10100-1 Winter 2004 Lecture 7.

28

Perl Precedence Rules

1. Operators within parentheses2. Exponential operators3. Multiplication and division operators4. Addition and subtraction operatorsConsider the following

$X = 100 – 3 ** 2 * 2; $Y = 100 – ((3 ** 2) * 2);$Z = 100 – ( 3 ** (2 * 2) );

Evaluates to 82

Evaluates to 19

Page 29: Introduction to Programming the WWW I CMSC 10100-1 Winter 2004 Lecture 7.

29

Prelim: Generating HTML with Perl Script

• Use MIME type text/html instead of text/plainprint “Content-type: text/html\n\n”;

• Add HTML codes in print()print “<HTML> <HEAD> <TITLE> Example </TITLE></HEAD>”;

Can use single quotes when output some HTML tags:print ‘<FONT COLOR=”BLUE”>’;

Can use backslash (“\”) to signal that double quotation marks themselves should be output:

print “<FONT COLOR=\”$color\”>”;

Page 30: Introduction to Programming the WWW I CMSC 10100-1 Winter 2004 Lecture 7.

30

Variables with HTML Output - II1. #!/usr/local/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.

Page 31: Introduction to Programming the WWW I CMSC 10100-1 Winter 2004 Lecture 7.

31

Would Output The Following ...

Run in Perl Builder

Page 32: Introduction to Programming the WWW I CMSC 10100-1 Winter 2004 Lecture 7.

32

Basics of Perl Functions • Perl includes built-in functions that provide

powerful additional capabilities to enhance your programs Work much like operators, except that most

(but not all) accept one or more arguments (I.e., input values into functions).

function_name (argument1, argument2, argument3);

Comma separate each inputargument to function.

Name of the function.

Usually enclose arguments in parentheses.

Page 33: Introduction to Programming the WWW I CMSC 10100-1 Winter 2004 Lecture 7.

33

The print Function

• You can enclose output in parentheses or not

• When use double quotation marks, Perl outputs the value of any variables. For example,

$x = 10;print ("Mom, please send $x dollars");

• Output the following message: Mom, please send 10 dollars

Page 34: Introduction to Programming the WWW I CMSC 10100-1 Winter 2004 Lecture 7.

34

More on print()

• If want to output the actual variable name (and not its value), then use single quotation marks

$x = 10;print('Mom, please send $x dollars');

• Would output the following message:Mom, please send $x dollars

Page 35: Introduction to Programming the WWW I CMSC 10100-1 Winter 2004 Lecture 7.

35

Still More on print ()

• Support multiple arguments separated by comma Example:$x=5;print('Send $bucks', " need $x. No make that ",

5*$x); Outputs:

Send $bucks need 5. No make that 25

Page 36: Introduction to Programming the WWW I CMSC 10100-1 Winter 2004 Lecture 7.

36

Assignment Operators

• Use the = sign as an assignment operator to assign values to a variable Variable = value;

• Precede the = sign with the arithmetic operators $revenue+=10; is equal to $revenue=$revenue+10;

Page 37: Introduction to Programming the WWW I CMSC 10100-1 Winter 2004 Lecture 7.

37

Assignment Operators

Operator Function= Normal Assignment+= Add and Assign-= Subtract and Assign*= Multiply and Assign/= Divide and Assign%= Modulus and Assign**= Exponent and Assign

Page 38: Introduction to Programming the WWW I CMSC 10100-1 Winter 2004 Lecture 7.

38

Increment/Decrement

Operator Function++ Increment (Add 1)-- Decrement (Subtract 1)

• ++ and -- can be added before or after a variable and will be evaluated differently

• Example 1:$revenue=5; $total= ++$revenue + 10;

• Example 1:$revenue=5; $total= $revenue++ + 10;

$revenue = 6$total=16

$total = 15$revenue=6

Page 39: Introduction to Programming the WWW I CMSC 10100-1 Winter 2004 Lecture 7.

39

String Operations

• 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

Page 40: Introduction to Programming the WWW I CMSC 10100-1 Winter 2004 Lecture 7.

40

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• Note … can use Double Quotation marks

$Fullname2 = “$FirstName $LastName”; Same as $Fullname2 = $FirstName . “ “ . $LastName; Single Quotation will treat the variable literally

Page 41: Introduction to Programming the WWW I CMSC 10100-1 Winter 2004 Lecture 7.

41

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.

Page 42: Introduction to Programming the WWW I CMSC 10100-1 Winter 2004 Lecture 7.

42

A Full Program Example ...

1. #!/usr/local/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>";

ConcatenateRepeat

Page 43: Introduction to Programming the WWW I CMSC 10100-1 Winter 2004 Lecture 7.

43

Would Output The Following ...

Run in Perl Builder

Page 44: Introduction to Programming the WWW I CMSC 10100-1 Winter 2004 Lecture 7.

44

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.

Page 45: Introduction to Programming the WWW I CMSC 10100-1 Winter 2004 Lecture 7.

45

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 used with an if statement • 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• specifies a set of statements to execute when one or more test

conditions are false.

Page 46: Introduction to Programming the WWW I CMSC 10100-1 Winter 2004 Lecture 7.

46

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.

Page 47: Introduction to Programming the WWW I CMSC 10100-1 Winter 2004 Lecture 7.

47

Numerical Test OperatorsNumerical

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.

<= Less than or equal to

if ($x <= $y) { print “y=$y”; print “x=$x”; }

Execute the second and third statements if the value of $x is less than or equal to the value of $y.

Page 48: Introduction to Programming the WWW I CMSC 10100-1 Winter 2004 Lecture 7.

48

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>”;

Page 49: Introduction to Programming the WWW I CMSC 10100-1 Winter 2004 Lecture 7.

49

Would Output The Following ...

Run in Perl Builder

Page 50: Introduction to Programming the WWW I CMSC 10100-1 Winter 2004 Lecture 7.

50

String Test Operators • Perl supports a set of string test operators that

are based on ASCII code values. ASCII code is a 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”.

Page 51: Introduction to Programming the WWW I CMSC 10100-1 Winter 2004 Lecture 7.

51

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.

Page 52: Introduction to Programming the WWW I CMSC 10100-1 Winter 2004 Lecture 7.

52

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 wheni f condi t i on i s

true.Execute these wheni ts condi t i on i strue but previ ous

i s f al se.Executedregardl ess of theprevi oustest condi t i ons.

Page 53: Introduction to Programming the WWW I CMSC 10100-1 Winter 2004 Lecture 7.

53

The elsif Clause 1. #!/usr/local/bin/perl 2. 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”;

Run in Perl Builder

Page 54: Introduction to Programming the WWW I CMSC 10100-1 Winter 2004 Lecture 7.

54

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.

Page 55: Introduction to Programming the WWW I CMSC 10100-1 Winter 2004 Lecture 7.

55

Using An else Clause

1.#!/usr/local/bin/perl 2.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.}

Page 56: Introduction to Programming the WWW I CMSC 10100-1 Winter 2004 Lecture 7.

56

Using unless

• The unless condition checks for a certain condition and executes it every time unless the condition is true. Sort of like the opposite of the if statement

• Example: unless ($gas_money == 10) {

print "You need exact change. 10 bucks please."; }