1 / 84

Introduction to Programming the WWW I

Introduction to Programming the WWW I. CMSC 10100-1 Summer 2004 Lecture 10. Today’s Topics. Perl data types and variables. Review: Perl Data Types. Scalars The simplest kind of data Perl can work with Either a string or number (integer, real, etc) Arrays of scalars

Download Presentation

Introduction to Programming the WWW I

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Introduction to Programming the WWW I CMSC 10100-1 Summer 2004 Lecture 10

  2. Today’s Topics • Perl data types and variables

  3. Review: 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

  4. Review: Perl Variables • Variables are containers to store and access data in computer memory • Variable names are not change in program • The stored data usually changes during execution • Three Variables in Perl • Scalar variables - hold a singular item such as a number (for example, 1, 1239.12, or –123) or a string (for example, “apple,” “ John Smith,” or “address”) • Array variables - hold a set of items • Hash variables – hold a set of key/value pairs

  5. Review: 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

  6. Review: Assigning New Values to Variables $X = 60; $Weeks = 4; $X = $Weeks; • Assigns 4 to $X and $Weeks. • Note: Perl variables are case sensitive • $xand $X are considered different variable names.

  7. 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 an underscore character • Less than 251 characters • Examples: • Valid: $baseball, $_sum, $X, $Numb_of_bricks, $num_houses, and$counter1 • Not Valid: $123go, $1counter, andcounter

  8. Variables and theprint • 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

  9. Would Output The Following:

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

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

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

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

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

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

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

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

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

  19. Arithmetic Operators

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

  21. Would Output The Following ...

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

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

  24. Review: 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 “<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\”>”;

  25. Variables with HTML Output - II 1. #!/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>”; Set blue font, size 5 Assign 28 Assign 2 Horizontal rule followed by black font.

  26. Would Output The Following ... • Run in Perl Builder

  27. 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;

  28. Assignment Operators

  29. Increment/Decrement • ++ 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

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

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

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

  33. A Full Program Example ... 1. #!/usr/local/bin/perl 2. 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

  34. Would Output The Following ... • Run in Perl Builder

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

  36. Conditional Statements • Perl supports 3 conditional clauses: • Anifstatement • specifiesa test condition and set of statements to execute when a test condition is true. • Anelsifclause used with an if statement • specifies an additional test condition to check when the previous test conditions are false. • Anelseclause is used with an ifstatementand possibly an elsif clause • specifies a set of statements to execute when one or more test conditions are false.

  37. 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 ifstatement. • When the test expression evaluates to true, then one or more additional statements within the required curly brackets ({ … }) are executed.

  38. Numerical Test Operators

  39. A Sample Conditional Program 1. #!/usr/bin/perl 2. 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>”;

  40. Would Output The Following ... • Run in Perl Builder

  41. 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 ASCIIcode 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”.

  42. String Test Operators

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

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

  45. The else Clause • Specifies a set of statements to execute when all other test conditions in anifblock 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.

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

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

  48. List Data • A list is an ordered collection of scalar values • Represented as a comma-separated list of values within parentheses • Example: (‘a’,2,3,”red”) • Use qw() function to generate a list • A list value usually stored in an array variable • An array variable is prefixed with a @ symbol

  49. Why use array variable? • Using array variables enable programs to: • Include a flexible number of list elements. You can add items to and delete items from lists on the fly in your program • Examine each element more concisely. Can use looping constructs (described later) with array variables to work with list items in a very concise manner • Use special list operators and functions. Can use to determine list length, output your entire list, and sort your list, & other things

  50. Creating List Variables • Suppose wanted to create an array variable to hold 4 student names: • Creates array variable @students with values ‘Johnson’, ‘Jones’, ‘Jackson’, and ‘Jefferson’

More Related