1 / 55

Chapter 5 List Variables and Loops

Chapter 5 List Variables and Loops. Objectives. Describe how list variables work Describe four types of Perl looping statements Explain how logical conditional operators are used. Lists Advantages. Using list variables enable programs to:

brobertson
Download Presentation

Chapter 5 List Variables and Loops

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. Chapter 5 List Variables and Loops

  2. Objectives • Describe how list variables work • Describe four types of Perl looping statements • Explain how logical conditional operators are used

  3. Lists Advantages • 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.

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

  5. Creating List Variables Of Scalars • 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.

  6. Referencing List Items • 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] • Reference in a variable name/subscript pair:

  7. Referencing List 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

  8. Creating List Variables Of Scalars • 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.

  9. Changing Items In A List Variable • 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 ) / 4—that is, to 80.

  10. 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 '<FORM ACTION="http://perl-pgm.com/cgi-bin/C5/choice.cgi" METHOD="POST">'; 7. print "<FONT SIZE=4 > What do you want to eat for dinner? "; 8. print br, "Our special is <FONT COLOR=BLUE> $menu[$item] </FONT>"; 9. print br, '<INPUT TYPE="RADIO" NAME="eat" VALUE="0">', "$menu[0]"; 10. print br, '<INPUT TYPE="RADIO" NAME="eat" VALUE="1" checked>', "$menu[1]"; 11. print br, '<INPUT TYPE="RADIO" NAME="eat" VALUE="2">', "$menu[2]"; 12. print br, '<INPUT TYPE="RADIO" NAME="eat" VALUE="3">', "$menu[3]"; 13. print br, '<INPUT TYPE=SUBMIT VALUE="Submit">'; 14.print '<INPUT TYPE=RESET></FORM>', end_html

  11. Would Output The Following ...

  12. Outputting the Entire List Variable • Output all of the elements of a list variable by using the list 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

  13. Getting the Number in a List Variable • Use Range operator to find last element of list • For example: @grades = ( 66, 75, 85, 80 ); $last_one = $grades[$#grades];

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

  15. 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 "<FONT size=4> 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;

  16. Would Output The Following ...

  17. A Better Way to Get List Length • 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;

  18. Adding and Removing List Items • shift()andunshift(): 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

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

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

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

  22. Extracting Multiple List Values • 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"; • would output: essentials=lettuce

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

  24. Extracting Multiple List Values • In a similar fashion, you can use a list variableas an index into another list variable. • Consider the following code @myList = ( 'hot dogs’, 'ketchup', 'lettuce', 'celery'); @keyones = ( 0, 3 ); @essentials = @myList[ @keyones ]; print "essentials=@essentials"; • The output of this code is essentials=hot dogs celery • Useful with certain HTML form elements.

  25. 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 '<FONT SIZE=4 > 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, '<INPUT TYPE=SUBMIT VALUE="Submit">'; 12. print '<INPUT TYPE=RESET></FORM>', end_html;

  26. Would Output The Following ...

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

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

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

  30. A Complete Example ... • Suppose the following HTML code creates radio buttons and sets CGI variable item (0-3) • The output is sent tohttp://perl-pgm.com/cgi-bin/C5/GetInvent.cgi. <BR><INPUT TYPE=radio NAME="item" VALUE=0 >Hammers <BR><INPUT TYPE=radio NAME="item" VALUE=1 >Wrenches <BR><INPUT TYPE=radio NAME="item" VALUE=2 >Hand Saws <BR><INPUT TYPE=radio NAME="item" VALUE=3 >Screw Drivers

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

  32. Would Output The Following ...

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

  34. Advantages of Using Loops

  35. The Perl Looping Constructs • Perl supports four types of looping constructs: • The for loop • The foreach loop • The while loop • The until loop • Each type of loop is described below.

  36. The for loop • You use the for loop to repeat a section of codea specified number of times. • (typically used when you know how many times to repeat)

  37. 3 Parts to the for Loop • The initialization expression defines the initial value of a variable used to control the loop. ($iis 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 $iduring each iteration of the loop. )

  38. 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><TH>Numb</TH><TH>Sqr</TH><TH>Cubed</TH>'; 7. for ( $i = $start; $i < $end; $i++ ) { 8. $i_sq=$i**2; 9. $i_cubed=$i**3; 10. print "<TR><TD> $i </TD> <TD> $i_sq </TD> <TD> $i_cubed </TR>"; 11. } 12. print "</TABLE>That is the end and i=$i"; 13. print end_html;

  39. Would Output The Following ...

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

  41. 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<BR>"; 11. $found=1; 12.last; 13. } 14. } 15. if ( $found ) { 16. print "<BR> I checked $ctr item(s)."; 17. } else { 18. print "<BR>Your guess, $uinput was NOT FOUND! I checked $ctr item(s)."; 19. }

  42. Would Output The Following ...

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

  44. 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 ( "<FONT Size=4> Numb of times to find $upick " ); 7. print ( '<TABLE BORDER=1> <TH> Numb <TH> Rand ' ); 8. $rnum= int(rand(10)); 9. while ( $rnum != $upick ) { 10. print ("<TR> <TD> $ctr <TD> $rnum </TR>"); 11. $ctr = $ctr + 1; 12. $rnum= int(rand(10)); 13. } 14. print ("<TR> <TD> $ctr <TD> $rnum </TR>"); 15. print ('</TABLE>', br, "FOUND in $ctr times random=$rnum" );

  45. Would Output The Following ...

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

  47. 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 ( "<FONT Size=4> Numb of times to find $upick " ); 7. print ( '<TABLE BORDER=1> <TH> Numb <TH> Rand ' ); 8. do { 9. $rnum= int(rand(10)); 10. print ("<TR> <TD> $ctr <TD> $rnum </TR>"); 11. $ctr = $ctr + 1; 12. } until ( $rnum == $upick ); 13. print ('</TABLE>', br, "FOUND in $ctr times random=$rnum" );

  48. 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 • For example, while ( $x > $max && $found ne ‘TRUE’ )

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

More Related