Presentation is loading. Please wait.

Presentation is loading. Please wait.

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

Similar presentations


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

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

2 2 Today’s Topics Variables and operators (lec7) Conditional statements (lec7) List (array) and hash Loop statements

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

24 24 Advantages of Using Loops

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

26 26 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)

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

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

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

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

31 31 Would Output The Following...

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

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

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

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

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

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

38 38 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) )

39 39 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 Winter 2004 Lecture 8."

Similar presentations


Ads by Google