Introduction to Programming the WWW I - PowerPoint PPT Presentation

About This Presentation
Title:

Introduction to Programming the WWW I

Description:

The simplest kind of data Perl can work with. Either a string ... Marks are strictest form of quotes. Everything between single quotes will be printed literally ... – PowerPoint PPT presentation

Number of Views:23
Avg rating:3.0/5.0
Slides: 85
Provided by: robert306
Category:

less

Transcript and Presenter's Notes

Title: Introduction to Programming the WWW I


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

2
Todays 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 variables 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
  • x and 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, and counter

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
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
  • x5
  • print('Send bucks', " need x. No make that ",
  • 5x)
  • 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.
  • lettersabc
  • fruitapple

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
    _at_
  • 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 ltHTMLgt ltHEADgt ltTITLEgt Example
    lt/TITLEgtlt/HEADgt
  • Can use single quotes when output some HTML tags
  • print ltFONT COLORBLUEgt
  • Can use backslash (\) to signal that double
    quotation marks themselves should be output
  • print ltFONT COLOR\color\gt

25
Variables with HTML Output - II
  • 1. !/usr/local/bin/perl
  • 2. print Content-type text/html\n\n
  • 3. print ltHTMLgt ltHEADgt ltTITLEgt Example
    lt/TITLEgtlt/HEADgt
  • 4. print ltBODYgt ltFONT COLORBLUE SIZE5gt
  • 5. num_week 8
  • 6. total_day num_week 7
  • 7. num_months num_week / 4
  • 8. print Number of days are total_day lt/FONTgt
  • 9. print ltHRgtThe total number of
    monthsnum_months
  • 10. print lt/BODYgtlt/HTMLgt

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
  • revenue10 is equal to revenuerevenue10

28
Assignment Operators
Operator Function
Normal Assignment
Add and Assign
- Subtract and Assign
Multiply and Assign
/ Divide and Assign
Modulus and Assign
Exponent and Assign
29
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
  • revenue5
  • total revenue 10
  • Example 1
  • revenue5
  • total revenue 10

revenue 6 total16
total 15 revenue6
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 FullName1FullName1 and
  • Fullname2FullName2
  • Would output the following
  • FullName1Bulland Bear and FullName2Bull 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_scoreslots_of_scores
  • Would output the following
  • lots_of_scoresGoal!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 "ltHTMLgt ltHEADgtltTITLEgt String
    Examplelt/TITLEgtlt/HEADgt"
  • 4. print "ltBODYgt"
  • 5. first "John"
  • 6. last "Smith"
  • 7. name first . last
  • 8. triple name x 3
  • 9. print "ltBRgt namename"
  • 10.print "ltBRgt triple triple"
  • 11. print "lt/BODYgtlt/HTMLgt"

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
  • 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
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
Numerical Test Operators
39
A Sample Conditional Program
  • 1. !/usr/bin/perl
  • 2. print "Content-type text/html\n\n"
  • 3. print "ltHTMLgt ltHEADgtltTITLEgt String Example
    lt/TITLEgtlt/HEADgt"
  • 4. print "ltBODYgt"
  • 5. grade 92
  • 6. if ( grade gt 89 )
  • 7. print ltFONT COLORBLUEgt
  • Hey you got an A.lt/FONTgtltBRgt
  • 8.
  • 9. print Your actual score was grade
  • 10. print lt/BODYgtlt/HTMLgt

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 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
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 gt 100 ) 5. print Illegal
Grade gt 100 6. 7. elsif ( grade lt 0 )
8. print illegal grade lt 0 9. 10.elsif
( grade gt 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 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
Using An else Clause
  • 1.!/usr/local/bin/perl
  • 2.print Content-type text/html\n\n
  • 3.grade 92
  • 4.if ( grade gt 100 )
  • 5. print Illegal Grade gt 100
  • 6.
  • 7.elsif ( grade lt 0 )
  • 8. print illegal grade lt 0
  • 9.
  • 10.elsif ( grade gt 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 _at_ 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 _at_students with values
    Johnson, Jones, Jackson, and Jefferson

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

52
Referencing Array Items
  • Items within an array variable are referenced by
    a set of related scalar variables
  • For example,
  • students0, students1, students2, and
    students3
  • Reference in a variable name/subscript pair

53
Referencing Array Items - II
  • Subscripts can be whole numbers, another
    variable, or even expressions enclosed within the
    square brackets.
  • Consider the following example
  • i3
  • _at_preferences (ketchup , mustard ,
  • pickles , lettuce )
  • print preferencesi preferencesi-1
  • preferencesi-2 preferences0
  • Outputs the list in reverse order
  • lettuce pickles mustard ketchup

54
Changing Items In An Array Variable
  • Change values in an array variable and use them
    in expressions like other scalar variables. For
    example
  • _at_scores ( 75, 65, 85, 90)
  • scores3 95
  • average ( scores0 scores1
  • scores2 scores3 ) / 4
  • The third line sets average equal to (75 65
    85 95 ) / 4, that is, to 80.

55
A Complete Array Example Program
  • 1. !/usr/local/bin/perl
  • 2. _at_menu ('Meat Loaf','Meat Pie','Minced
    Meat', 'Meat Surprise')
  • 3. print "What do you want to eat for
    dinner?\n"
  • 4. print 1. menu0"
  • 5. print 2. menu1"
  • 6. print 3. menu2"
  • 7. print 4. menu3"
  • Run in Perl Builder

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

57
Getting the Number in an Array Variable
  • Use Range operator to find last element of list
  • For example
  • _at_grades ( 66, 75, 85, 80 )
  • last_one gradesgrades

grades3
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).
  • _at_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
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
    _at_grades
  • size_at_grades

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,
  • _at_workWeek (Monday, Tuesday,
    Wednesday,Thursday, Friday )
  • dayOff shift(_at_workWeek)
  • print "dayOff dayOff workWeek_at_workWeek"
  • Would output the following
  • dayOff Monday workWeekTuesday Wednesday
    Thursday Friday

61
Adding and Removing List Items
  • unshift() adds an element to the beginning of
    the list For example,
  • _at_workWeek (Monday, Tuesday, Wednesday,
  • Thursday, Friday )
  • unshift(_at_workWeek, Sunday)
  • print workWeek is now _at_workWeek
  • would output the following
  • workWeek is now Sunday Monday Tuesday Wednesday
    Thursday Friday

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,
  • _at_workWeek (Monday, Tuesday, Wednesday,
    Thursday, Friday )
  • dayOff pop(_at_workWeek)
  • Would output the following
  • dayOff Friday workWeekMonday Tuesday Wednesday
    Thursday

63
Adding and Removing List Items
  • push() adds an element to the end of the list
    For example,
  • _at_workWeek (Monday, Tuesday, Wednesday,
  • Thursday, Friday )
  • push(_at_workWeek, Saturday)
  • print workWeek is now _at_workWeek
  • would output the following
  • workWeek is now Monday Tuesday Wednesday
    Thursday Friday Saturday

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,
  • _at_myList ( 'hot dogs, 'ketchup', 'lettuce',
    'celery')
  • _at_essentials _at_myList 2, 3
  • print "essentials_at_essentials"
  • The output of this code is
  • essentialslettuce celery

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

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,
  • Inventory00 points to AC1000,
  • Inventory10 points to AC1001, and
  • Inventory20 points to AC1002

67
A Partial Example ...
  • _at_Inventory (
  • 'AC1000', 'Hammer', 122, 12.50 ,
  • 'AC1001', 'Wrench', 344, 5.50 ,
  • 'AC1002', 'Hand Saw', 150, 10.00
  • )
  • numHammers Inventory02
  • firstPartNo Inventory00
  • Inventory03 15
  • print numHammers, firstPartNo,Inventory03
  • This would output
  • 122, AC1000, 15

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
Advantages of Using Loops
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
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
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
for loop example
  • 1. !/usr/local/bin/perl
  • 2. print 'The sum from 1 to 5 is '
  • 3. sum 0
  • 4. for (count1 countlt6 count)
  • 5. sum count
  • 6.
  • 7. print "sum\n"
  • This would output
  • The sum from 1 to 5 is 15
  • Run in Perl Builder

74
The foreach Loop
  • The foreach loop is typically used to repeat a
    set of statements for each item in an array
  • If _at_items_array (A, B, C)
  • Then item would A then B then C.

75
foreach Example
  • 1. !/usr/local/bin/perl
  • 2. _at_secretNums ( 3, 6, 9 )
  • 3.uinput 6
  • 4. ctr0 found 0
  • 5. foreach item ( _at_secretNums )
  • 6. ctrctr1
  • 7. if ( item uinput )
  • print "Number item. Item found was number
    ctrltBRgt"
  • found1
  • last
  • 10.
  • 11.
  • 12.if (!found)
  • print Could not find the number/n

The last statement will Force an exit of the loop
  • Run in Perl Builder

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

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 count1
  • 4. while (count lt 6)
  • sum count
  • count
  • 7.
  • 8. print "sum\n"
  • Run in Perl Builder

79
Hw3 discussion
  • Problem3 using while loop to read input from
    command line
  • while the program is running, it will return
  • to this point and wait for input
  • while (ltgt)
  • input _
  • chomp(input)
  • ltgt 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

chomp() is a built-in function to remove the
end-of-line character of a string
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
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 count1
  • 4. do
  • sum count
  • count
  • 7. until (count gt 6)
  • 8. print "sum\n"

until loop must end with a
  • Run in Perl Builder

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 gt max found ne TRUE )
  • will test if x greater than max AND found is
    not equal to TRUE

83
Some Basic Logical Operators
  • the AND operator - True if both tests must be
    true
  • while ( ctr lt 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
Consider the following ...
  • 1. !/usr/local/bin/perl
  • 2. _at_safe (1, 7)
  • 3. print ('My Personal Safe')
  • 4. in1 1
  • 5. in2 6
  • 6. if (( in1 safe0 ) ( in2
    safe1))
  • 7. print "Congrats you got the combo"
  • 8. elsif(( in1 safe0 ) ( in2
    safe1))
  • 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
Write a Comment
User Comments (0)
About PowerShow.com