Presentation is loading. Please wait.

Presentation is loading. Please wait.

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

Similar presentations


Presentation on theme: "Introduction to Programming the WWW I CMSC 10100-1 Winter 2004 Lecture 7."— Presentation transcript:

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

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

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

4 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

5 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

6 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

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

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

9 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

10 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

11 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

12 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

13 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

14 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

15 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

16 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.

17 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/perl 2. 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 $y

18 18 Would Output The Following:

19 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

20 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 Single quotes examples

21 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

22 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

23 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

24 24 Arithmetic Operators

25 25 Example Program 1. #!/usr/local/bin/perl 2. 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 $cubed Assign 55 to $cubed $remain is remainder of 28 / 3 or 1

26 26 Would Output The Following...

27 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

28 28 Perl Precedence Rules 1. Operators within parentheses 2. Exponential operators 3. Multiplication and division operators 4. Addition and subtraction operators Consider the following $X = 100 – 3 ** 2 * 2; $Y = 100 – ((3 ** 2) * 2); $Z = 100 – ( 3 ** (2 * 2) ); Evaluates to 82 Evaluates to 19

29 29 Prelim: Generating HTML with Perl Script Use MIME type text/html instead of text/plain print “Content-type: text/html\n\n”; Add HTML codes in print() print “ Example ”;  Can use single quotes when output some HTML tags: print ‘ ’;  Can use backslash (“ \ ”) to signal that double quotation marks themselves should be output: print “ ”;

30 30 Variables with HTML Output - II 1. #!/usr/local/bin/perl 2. print “Content-type: text/html\n\n”; 3. print “ Example ”; 4. print “ ”; 5. $num_week = 8; 6. $total_day = $num_week * 7; 7. $num_months = $num_week / 4; 8. print “Number of days are $total_day ”; 9. print “ The total number of months=$num_months”; 10. print “ ”; Assign 28 Assign 2 Set blue font, size 5 Horizontal rule followed by black font.

31 31 Would Output The Following...  Run in Perl Builder Run in Perl Builder

32 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).

33 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

34 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

35 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

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

37 37 Assignment Operators OperatorFunction =Normal Assignment +=Add and Assign -=Subtract and Assign *=Multiply and Assign /=Divide and Assign %=Modulus and Assign **=Exponent and Assign

38 38 Increment/Decrement OperatorFunction ++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

39 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

40 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

41 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 value 3 times.

42 42 A Full Program Example... 1. #!/usr/local/bin/perl 2. print "Content-type: text/html\n\n"; 3. print " String Example "; 4. print " "; 5. $first = "John"; 6. $last = "Smith"; 7. $name = $first. $last; 8. $triple = $name x 3; 9. print " name=$name"; 10.print " triple = $triple"; 11. print " "; Concatenate Repeat

43 43 Would Output The Following...  Run in Perl Builder Run in Perl Builder

44 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.

45 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.

46 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.

47 47 Numerical Test Operators

48 48 A Sample Conditional Program 1. #!/usr/bin/perl 2. print "Content-type: text/html\n\n"; 3. print " String Example "; 4. print " "; 5. $grade = 92; 6. if ( $grade > 89 ) { 7. print “ Hey you got an A. ”; 8. } 9. print “Your actual score was $grade”; 10. print “ ”;

49 49 Would Output The Following...  Run in Perl Builder Run in Perl Builder

50 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. ASCII code  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”.

51 51 String Test Operators

52 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

53 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 Run in Perl Builder

54 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.

55 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. }

56 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."; }


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

Similar presentations


Ads by Google