Presentation is loading. Please wait.

Presentation is loading. Please wait.

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

Similar presentations


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

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

2 2 Today’s Topics Perl data types and variables

3 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 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 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 6 $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. Review: Assigning New Values to Variables

7 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, and counter

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

9 9 Would Output The Following:

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

18 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 19 Arithmetic Operators

20 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 21 Would Output The Following...

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

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

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

27 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 28 Assignment Operators OperatorFunction =Normal Assignment +=Add and Assign -=Subtract and Assign *=Multiply and Assign /=Divide and Assign %=Modulus and Assign **=Exponent and Assign

29 29 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

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

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

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

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

38 38 Numerical Test Operators

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

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

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

42 42 String Test Operators

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

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

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

51 51 Creating Array Variables Of Scalars Suppose wanted to create an array variable to hold 4 student grades (numerical values): @grades = ( 66, 75, 85, 80 ); Creates array variable @grades with values 66, 75, 85, 80.

52 52 Referencing Array Items Items within an array variable are referenced by a set of related scalar variables For example, $students[0], $students[1], $students[2], and $students[3] Reference in a variable name/subscript pair:

53 53 Referencing Array Items - II Subscripts can be whole numbers, another variable, or even expressions enclosed within the square brackets. Consider the following example: $i=3; @preferences = (“ketchup ”, “mustard ”, “pickles ”, “lettuce ” ); print “$preferences[$i] $preferences[$i-1] $preferences[$i-2] $preferences[0]”; Outputs the list in reverse order: lettuce pickles mustard ketchup

54 54 Changing Items In An Array Variable Change values in an array variable and use them in expressions like other scalar variables. For example:  @scores = ( 75, 65, 85, 90);  $scores[3] = 95;  $average = ( $scores[0] + $scores[1] +  $scores[2] + $scores[3] ) / 4; The third line sets $average equal to (75 + 65 + 85 + 95 ) / 4, that is, to 80.

55 55 A Complete Array Example Program 1. #!/usr/local/bin/perl 2. @menu = ('Meat Loaf','Meat Pie','Minced Meat', 'Meat Surprise'); 3. print "What do you want to eat for dinner?\n"; 4. print “1. $menu[0]"; 5. print “2. $menu[1]"; 6. print “3. $menu[2]"; 7. print “4. $menu[3]";  Run in Perl Builder Run in Perl Builder

56 56 Outputting the Entire Array Variable Output all of the elements of an array variable by using the array variable with print For example, @workWeek = ('Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday' ); print "My work week is @workWeek"; Would output the following:  My work week is Monday Tuesday Wednesday Thursday Friday

57 57 Getting the Number in an Array Variable Use Range operator to find last element of list For example: @grades = ( 66, 75, 85, 80 ); $last_one = $grades[$#grades]; $#grades=3

58 58 Using Range Operator for list length Ranger operator is always 1 less than the total number in the list  (since list start counting at 0 rather than 1). @workWeek = (‘Monday’, ‘Tuesday’, ‘Wednesday’, ‘Thursday’, ‘Friday’ ); $daysLong = $#workWeek + 1; print “My work week is $daysLong days long”; Would output the following message: My work week is 5 days long.

59 59 A Better Way to Get List Length You can also find the length of an array variable by assigning the array variable name to a scalar variable For example, the following code assigns to $size the number of elements in the array variable @grades :  $size=@grades;

60 60 Adding and Removing List Items shift() and unshift() : add/remove elements from the beginning of a list.  shift() removes an item from the beginning of a list. For example, @workWeek = (‘Monday’, ‘Tuesday’, ‘Wednesday’,‘Thursday’, ‘Friday’ ); $dayOff = shift(@workWeek); print "dayOff= $dayOffworkWeek=@workWeek";  Would output the following: dayOff= Monday workWeek=Tuesday Wednesday Thursday Friday

61 61 Adding and Removing List Items  unshift() adds an element to the beginning of the list For example, @workWeek = (‘Monday’, ’Tuesday’, ’Wednesday’, ’Thursday’, ’Friday’ ); unshift(@workWeek, “Sunday”); print “workWeek is now =@workWeek”;  would output the following: workWeek is now =Sunday Monday Tuesday Wednesday Thursday Friday

62 62 Adding and Removing List Items pop() and push ( ) : add/remove elements from the end of a list.  pop() removes an item from the end of a list. For example, @workWeek = (“Monday”, “Tuesday”, “Wednesday”, “Thursday”, “Friday” ); $dayOff = pop(@workWeek);  Would output the following dayOff= Friday workWeek=Monday Tuesday Wednesday Thursday

63 63 Adding and Removing List Items  push() adds an element to the end of the list For example, @workWeek = (‘Monday’, ‘Tuesday’, ‘Wednesday’, ‘Thursday’, ‘Friday’ ); push(@workWeek, ‘Saturday’); print “workWeek is now =@workWeek”;  would output the following: workWeek is now =Monday Tuesday Wednesday Thursday Friday Saturday

64 64 Extracting Multiple List Values If you use multiple subscripts for a list variable, you will extract a sub-list with the matching list items. For example, @myList = ( 'hot dogs’, 'ketchup', 'lettuce', 'celery'); @essentials = @myList[ 2, 3 ]; print "essentials=@essentials"; The output of this code is essentials=lettuce celery

65 65 Lists of Lists (or multidimensional lists) Some data are best represented by a list of lists

66 66 Accessing Individual Items Use multiple subsripts to access individual items  The first subscript indicates the row in which the item appears, and  the second subscript identifies the column where it is found.  In the preceding example, $Inventory[0][0] points to AC1000, $ Inventory[1][0] points to AC1001, and $Inventory[2][0] points to AC1002

67 67 A Partial Example... @Inventory = ( [ 'AC1000', 'Hammer', 122, 12.50 ], [ 'AC1001', 'Wrench', 344, 5.50 ], [ 'AC1002', 'Hand Saw', 150, 10.00] ); $numHammers = $Inventory[0][2]; $firstPartNo = $Inventory[0][0]; $Inventory[0][3] = 15; print “$numHammers, $firstPartNo,$Inventory[0][3]”; This would output 122, AC1000, 15

68 68 Looping Statements Advantages of using loops:  Your programs can be much more concise. When similar sections of statements need to be repeated in your program, you can often put them into a loop and reduce the total number of lines of code required.  You can write more flexible programs. Loops allow you to repeat sections of your program until you reach the end of a data structure such as a list or a file (covered later).

69 69 Advantages of Using Loops

70 70 The Perl Looping Constructs Perl supports four types of looping constructs:  The for loop  The foreach loop  The while loop  The until loop They can be replaced by each other

71 71 The for loop You use the for loop to repeat a section of code a specified number of times  (typically used when you know how many times to repeat)

72 72 3 Parts to the for Loop The initialization expression defines the initial value of a variable used to control the loop. ( $i is used above with value of 0). The loop-test condition defines the condition for termination of the loop. It is evaluated during each loop iteration. When false, the loop ends. (The loop above will repeat as long as $i is less than $max). The iteration expression is evaluated at end of each loop iteration. (In above loop the expression $i++ means to add 1 to the value of $i during each iteration of the loop. )

73 73 for loop example 1. #!/usr/local/bin/perl 2. print 'The sum from 1 to 5 is: '; 3. $sum = 0; 4. for ($count=1; $count<6; $count++){ 5. $sum += $count; 6. } 7. print "$sum\n"; This would output The sum from 1 to 5 is: 15  Run in Perl Builder Run in Perl Builder

74 74 The foreach Loop The foreach loop is typically used to repeat a set of statements for each item in an array If @items_array = (“A”, “B”, “C”);  Then $item would “A” then “B” then “C”.

75 75 foreach Example 1. #!/usr/local/bin/perl 2. @secretNums = ( 3, 6, 9 ); 3.$uinput = 6; 4. $ctr=0; $found = 0; 5. foreach $item ( @secretNums ) { 6. $ctr=$ctr+1; 7. if ( $item == $uinput ) { print "Number $item. Item found was number $ctr "; 8. $found=1; 9. last; 10. } 11. } 12.if (!$found){ 13. print “Could not find the number/n”; 14.} The last statement will Force an exit of the loop  Run in Perl Builder Run in Perl Builder

76 76 Would Output The Following...

77 77 The while Loop You use a while loop to repeat a section of code as long as a test condition remains true.

78 78 Consider The Following... Calculation of sum from 1 to 5 1. #!/usr/local/bin/perl 2. print 'The sum from 1 to 5 is: '; 3. $sum = 0; $count=1; 4. while ($count < 6){ 5. $sum += $count; 6. $count++; 7. } 8. print "$sum\n";  Run in Perl Builder Run in Perl Builder

79 79 Hw3 discussion Problem3: using while loop to read input from command line Problem3 # while the program is running, it will return # to this point and wait for input while (<>){ $input = $_; chomp($input); … } <> is the input operator (angle operator) with a included file handle  Empty file handle = STDIN $_ is a special Perl variable  It is set as each input line in this example Flowchart my example Flowchartmy example chomp() is a built-in function to remove the end-of-line character of a string

80 80 The until Loop Operates just like the while loop except that it loops as long as its test condition is false and continues until it is true

81 81 Example Program Calculation of sum from 1 to 5 1. #!/usr/local/bin/perl 2. print 'The sum from 1 to 5 is: '; 3. $sum = 0; $count=1; 4. do { 5. $sum += $count; 6. $count++; 7. }until ($count >= 6); 8. print "$sum\n"; until loop must end with a ;  Run in Perl Builder Run in Perl Builder

82 82 Logical Operators (Compound Conditionals) logical conditional operators can test more than one test condition at once when used with if statements, while loops, and until loops For example, while ( $x > $max && $found ne ‘TRUE’ ) will test if $x greater than $max AND $found is not equal to ‘TRUE’

83 83 Some Basic Logical Operators && —the AND operator - True if both tests must be true: while ( $ctr < $max && $flag == 0 ) || —the OR operator. True if either test is true if ( $name eq “SAM” || $name eq “MITCH” ) ! —the NOT operator. True if test false if ( !($FLAG == 0) )

84 84 Consider the following... 1. #!/usr/local/bin/perl 2. @safe = (1, 7); 3. print ('My Personal Safe'); 4. $in1 = 1; 5. $in2 = 6; 6. if (( $in1 == $safe[0] ) && ( $in2 == $safe[1])){ 7. print "Congrats you got the combo"; 8. }elsif(( $in1 == $safe[0] ) || ( $in2 == $safe[1])){ 9. print “You got half the combo"; 10. }else { 11. print "Sorry you are wrong! "; 12. print "You guessed $in1 and $in2 "; 13. }  Run in Perl Builder Run in Perl Builder


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

Similar presentations


Ads by Google