Download presentation
Presentation is loading. Please wait.
Published byJordan Young Modified over 11 years ago
1
1 Copyright © 2002 Pearson Education, Inc.
2
2 Chapter 5 List Variables and Loops
3
3 Copyright © 2002 Pearson Education, Inc. Objectives l Describe how list variables work l Describe four types of Perl looping statements l Explain how logical conditional operators are used
4
4 Copyright © 2002 Pearson Education, Inc. Lists Advantages l Using list 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 list 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 Copyright © 2002 Pearson Education, Inc. Creating List Variables l Suppose wanted to create a list variable to hold 4 student names: Creates list variable @students with values Johnson, Jones, Jackson, and Jefferson
6
6 Copyright © 2002 Pearson Education, Inc. Creating List Variables Of Scalars l Suppose wanted to create a list variable to hold 4 student grades (numerical values): @grades = ( 66, 75, 85, 80 ); Creates list variable @grades with values 66, 75, 85, 80.
7
7 Copyright © 2002 Pearson Education, Inc. Referencing List Items l Items within a list variable are referenced by a set of related scalar variables For example, $students[0], $students[1], $students[2], and $students[3] l Reference in a variable name/subscript pair:
8
8 Copyright © 2002 Pearson Education, Inc. Referencing List Items - II l Subscripts can be whole numbers, another variable, or even expressions enclosed within the square brackets. l Consider the following example: $i=3; @preferences = (ketchup, mustard, pickles, lettuce ); print $preferences[$i] $preferences[$i-1] $preferences[$i-2] $preferences[0]; l Outputs the list in reverse order: lettuce pickles mustard ketchup
9
9 Copyright © 2002 Pearson Education, Inc. Creating List Variables Of Scalars l Suppose wanted to create a list variable to hold 4 student grades (numerical values): @grades = ( 66, 75, 85, 80 ); Creates list variable @grades with values 66, 75, 85, 80.
10
10 Copyright © 2002 Pearson Education, Inc. Changing Items In A List Variable l Change values in a list 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 ) / 4that is, to 80.
11
11 Copyright © 2002 Pearson Education, Inc. A Complete List Example Program 1. #!/usr/bin/perl 2. use CGI ':standard'; 3. print header, start_html('Menu Choice'); 4. @menu = ('Meat Loaf', 'Meat Pie', 'Minced Meat', 'Meat Surprise' ); 5. $item = int(rand(4)); 6. print ' '; 7. print " What do you want to eat for dinner? "; 8. print br, "Our special is $menu[$item] "; 9. print br, ' ', "$menu[0]"; 10. print br, ' ', "$menu[1]"; 11. print br, ' ', "$menu[2]"; 12. print br, ' ', "$menu[3]"; 13. print br, ' '; 14.print ' ', end_html
12
12 Copyright © 2002 Pearson Education, Inc. Would Output The Following...
13
13 Copyright © 2002 Pearson Education, Inc. Outputting the Entire List Variable Output all of the elements of a list variable by using the list variable with print l For example, @workWeek = ('Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday' ); print "My work week is @workWeek"; l Would output the following: »My work week is Monday Tuesday Wednesday Thursday Friday
14
14 Copyright © 2002 Pearson Education, Inc. Getting the Number in a List Variable l Use Range operator to find last element of list l For example: @grades = ( 66, 75, 85, 80 ); $last_one = $grades[$#grades];
15
15 Copyright © 2002 Pearson Education, Inc. Using Range Operator for list length l 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; l Would output the following message: My work week is 5 days long.
16
16 Copyright © 2002 Pearson Education, Inc. Using Range Operator for list length 1. #!/usr/bin/perl 2. use CGI ':standard'; 3. print header, start_html("Got Your Preference"); 4. @menu = ("Meat Loaf", "Meat Pie", "Minced Meat", "Meat Surprise" ); 5. $response = param('eat'); 6. print " You Selected @menu[$response]"; 7. $menuLen = $#menu + 1; 8. print br, "We had $menuLen items available"; 9. print br, "These items were @menu", end_html;
17
17 Copyright © 2002 Pearson Education, Inc. Would Output The Following...
18
18 Copyright © 2002 Pearson Education, Inc. A Better Way to Get List Length l You can also find the length of a list variable by assigning the list variable name to a scalar variable. For example, the following code assigns to $size the number of elements in the list variable @grades : »$size=@grades;
19
19 Copyright © 2002 Pearson Education, Inc. 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= $dayOff workWeek=@workWeek"; »Would output the following: dayOff= Monday workWeek=Tuesday Wednesday Thursday Friday
20
20 Copyright © 2002 Pearson Education, Inc. 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
21
21 Copyright © 2002 Pearson Education, Inc. Adding and Removing List Items pop() and push( ) : add/remove elements from the end of a list. »shift() 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
22
22 Copyright © 2002 Pearson Education, Inc. 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
23
23 Copyright © 2002 Pearson Education, Inc. Extracting Multiple List Values l So for we have accessed one item at a time from a list variable. For example, @myList = ( 'hot dogs, 'ketchup', 'lettuce', 'celery'); $essentials = @myList[ 2 ]; print "essentials=$essentials"; l would output: essentials=lettuce
24
24 Copyright © 2002 Pearson Education, Inc. Extracting Multiple List Values l If you use multiple subscripts for a list variable, you will extract a sub-list with the matching list items. l For example, @myList = ( 'hot dogs, 'ketchup', 'lettuce', 'celery'); @essentials = @myList[ 2, 3 ]; print "essentials=@essentials"; l The output of this code is essentials=lettuce celery
25
25 Copyright © 2002 Pearson Education, Inc. Extracting Multiple List Values l In a similar fashion, you can use a list variable as an index into another list variable. l Consider the following code @myList = ( 'hot dogs, 'ketchup', 'lettuce', 'celery'); @keyones = ( 0, 3 ); @essentials = @myList[ @keyones ]; print "essentials=@essentials"; l The output of this code is essentials=hot dogs celery »Useful with certain HTML form elements.
26
26 Copyright © 2002 Pearson Education, Inc. Example Multiple Arguments 1. #!/usr/bin/perl 2. use CGI ':standard'; 3. print header; 4. @menu = ('USA', 'China', 'Canada', 'Mexico' ); 5. print '<FORM ACTION="http://perl-pgm.com/cgi- bin/C5/multichoice.cgi METHOD="POST">'; 6. print ' What countries have you visited?'; 7. print '<INPUT TYPE="checkbox" NAME="places" VALUE="0">', $menu[0]"; 8. print '<INPUT TYPE="checkbox" NAME="places" VALUE="1" checked>', "$menu[1]"; 9. print '<INPUT TYPE="checkbox" NAME="places" VALUE="2">', "$menu[2]"; 10. print '<INPUT TYPE="checkbox" NAME="places" VALUE="3">', "$menu[3]"; 11. print br, ' '; 12. print ' ', end_html;
27
27 Copyright © 2002 Pearson Education, Inc. Would Output The Following...
28
28 Copyright © 2002 Pearson Education, Inc. Lists of Lists (or multidimensional lists) l Some data are best represented by a list of lists
29
29 Copyright © 2002 Pearson Education, Inc. Accessing Individual Items l 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
30
30 Copyright © 2002 Pearson Education, Inc. 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]; l This would output 122, AC1000, 15
31
31 Copyright © 2002 Pearson Education, Inc. A Complete Example... Suppose the following HTML code creates radio buttons and sets CGI variable item (0-3) l The output is sent to http://perl-pgm.com/cgi- bin/C5/GetInvent.cgi. Hammers Wrenches Hand Saws Screw Drivers
32
32 Copyright © 2002 Pearson Education, Inc. Receiving CGI/Perl Program 1. #!/usr/bin/perl 2. use CGI ':standard'; 3. print header, start_html('Inventory Answer'); 4. # Inventory: PartNO, Item, Num In Stock, Price 5. $PRTNO=0; $ITEM=1; $NUM=2; $PRICE=3; 6. @Inventory = ( [ 'AC1000', 'Hammers', 122, 12 ], [ 'AC1001', 'Wrenches', 344, 5 ], [ 'AC1002', 'Hand Saws', 150, 10], [ 'AC1003', 'Screw Drivers', 250, 2] ); 7. $pick=param('item'); 8. if ( $pick >= 0 && $pick <= 3 ) { 9. print "Yes we have $Inventory[$pick][$ITEM]."; 10. print br, "In fact we have $Inventory[$pick][$NUM] of them."; 11. print br, "They are $Inventory[$pick][$PRICE] dollars."; 12. } else { "print sorry we do not have that item" } 13. print end_html;
33
33 Copyright © 2002 Pearson Education, Inc. Would Output The Following...
34
34 Copyright © 2002 Pearson Education, Inc. Looping Statements l 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).
35
35 Copyright © 2002 Pearson Education, Inc. Advantages of Using Loops
36
36 Copyright © 2002 Pearson Education, Inc. The Perl Looping Constructs l Perl supports four types of looping constructs: »The for loop » The foreach loop »The while loop »The until loop l Each type of loop is described below.
37
37 Copyright © 2002 Pearson Education, Inc. 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)
38
38 Copyright © 2002 Pearson Education, Inc. 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-ending 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. )
39
39 Copyright © 2002 Pearson Education, Inc. Consider the following program 1. #!/usr/bin/perl 2. use CGI ':standard'; 3. print header, start_html(For Loop); 4. $start = param ('start'); 5. $end = param ( 'end'); 6. print '<TABLE BORDER=1> Numb Sqr Cubed '; 7. for ( $i = $start; $i < $end; $i++ ) { 8. $i_sq=$i**2; 9. $i_cubed=$i**3; 10. print " $i $i_sq $i_cubed "; 11. } 12. print " That is the end and i=$i"; 13. print end_html;
40
40 Copyright © 2002 Pearson Education, Inc. Would Output The Following...
41
41 Copyright © 2002 Pearson Education, Inc. The foreach Loop The foreach loop is typically used to repeat a set of statements for every element in a list. If @items_array = (A, B, C); »Then $item would A then B then C.
42
42 Copyright © 2002 Pearson Education, Inc. A For Each Example Program 1. #!/usr/bin/perl 2. use CGI ':standard'; 3. print header, start_html(' A foreach Example'); 4. @secretNums = ( 3, 6, 9 ); 5. $uinput = param( 'guess' ); 6. $ctr=0; $found=0; 7. foreach $item ( @secretNums ) { 8. $ctr=$ctr+1; 9. if ( $item == $uinput ) { 10. print "Number $item. Item found was number $ctr "; 11. $found=1; 12. last; 13. } 14. } 15. if ( $found ) { 16. print " I checked $ctr item(s)."; 17. } else { 18. print " Your guess, $uinput was NOT FOUND! I checked $ctr item(s)."; 19. }
43
43 Copyright © 2002 Pearson Education, Inc. Would Output The Following...
44
44 Copyright © 2002 Pearson Education, Inc. The while Loop You use a while loop to repeat a section of code as long as a test condition remains true.
45
45 Copyright © 2002 Pearson Education, Inc. Consider The Following... 1. #!/usr/bin/perl 2. use CGI ':standard'; 3. print header, start_html(' A While Example'); 4. $upick=param('upick'); 5. $ctr = 1; 6. print ( " Numb of times to find $upick " ); 7. print ( ' Numb Rand ' ); 8. $rnum= int(rand(10)); 9. while ( $rnum != $upick ) { 10. print (" $ctr $rnum "); 11. $ctr = $ctr + 1; 12. $rnum= int(rand(10)); 13. } 14. print (" $ctr $rnum "); 15. print (' ', br, "FOUND in $ctr times random=$rnum" );
46
46 Copyright © 2002 Pearson Education, Inc. Would Output The Following...
47
47 Copyright © 2002 Pearson Education, Inc. 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
48
48 Copyright © 2002 Pearson Education, Inc. Example Program 1. #!/usr/bin/perl 2. use CGI ':standard'; 3. print header, start_html(' A While Example'); 4. $upick=param('upick'); 5. $ctr = 1; 6. print ( " Numb of times to find $upick " ); 7. print ( ' Numb Rand ' ); 8. do { 9. $rnum= int(rand(10)); 10. print (" $ctr $rnum "); 11. $ctr = $ctr + 1; 12. } until ( $rnum == $upick ); 13. print (' ', br, "FOUND in $ctr times random=$rnum" );
49
49 Copyright © 2002 Pearson Education, Inc. Creating Compound Conditionals logical conditional operators can test more than one test condition at once when used with if statements, while loops, and until loops l For example, while ( $x > $max && $found ne TRUE )
50
50 Copyright © 2002 Pearson Education, Inc. Some basic Conditional Operators && the AND operator - Both tests must be true: while ( $ctr < $max && $flag == 0 ) { || the OR operator. Either test is true. if ( $name eq SAM || $name eq MITCH ) { ! the NOT operator. Condition is false. if ( !$FLAG == 0 )
51
51 Copyright © 2002 Pearson Education, Inc. Consider the following... 1. #!/usr/bin/perl 2. use CGI ':standard'; 3. @safe = (1, 7); 4. print header, start_html('My Personal Safe'); 5. $in1 = param( 'pick1' ); 6. $in2 = param( 'pick2' ); 7. if (( $in1 == $safe[0] ) && ( $in2 == $safe[1])){ 8. print "Congrats you got the combo"; 9. } 10. else { 11. print "Sorry you are wrong! "; 12. print "You guessed $in1 and $in2 "; 13. } 14. print end_html;
52
52 Copyright © 2002 Pearson Education, Inc. Would Output The Following...
53
53 Copyright © 2002 Pearson Education, Inc. Summary l List variables offer a way to organize data in your program into one list instead of using individual scalar variables. »Data elements within a list can be accessed by a common variable name, which is made up of two parts: a variable name and subscript values. l Using list variables enables you to add and delete list items on the fly in your programs, use loop constructs to examine and operate on each item in your list, and utilize special list operators and functions.
54
54 Copyright © 2002 Pearson Education, Inc. Summary Loops can be especially useful for examining and operating on data organized into lists. Loop statements include the for, foreach, while, and until loops. l The logical operators can be used to carry out compound tests within a conditional test statement. –The logical AND operator, &&, evaluates to true when both conditions are true. – The logical OR operator, ||, evaluates to true when either condition is true. –The logical NOT operator, !, evaluates to true when the test condition is false.
55
55 Copyright © 2002 Pearson Education, Inc. Summary l The logical operators can be used to carry out compound tests within a conditional test statement. –The logical AND operator, &&, evaluates to true when both conditions are true. – The logical OR operator, ||, evaluates to true when either condition is true. –The logical NOT operator, !, evaluates to true when the test condition is false.
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.