1 copyright © 2002 pearson education, inc.. 2 chapter 5 list variables and loops

Post on 26-Mar-2015

216 Views

Category:

Documents

1 Downloads

Preview:

Click to see full reader

TRANSCRIPT

1 Copyright © 2002 Pearson Education, Inc.

2 Copyright © 2002 Pearson Education, Inc.

Chapter 5List Variables and Loops

3 Copyright © 2002 Pearson Education, Inc.

Objectives

Describe how list variables work Describe four types of Perl looping statements Explain how logical conditional operators are

used

4 Copyright © 2002 Pearson Education, Inc.

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.

5 Copyright © 2002 Pearson Education, Inc.

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’

@students = ('Johnson', 'Jones', 'Jackson', 'Jefferson' );

Comma separateeach list item.

List variablenames start

with "@" sign.

Enclose lists inparenthesis

6 Copyright © 2002 Pearson Education, Inc.

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.

7 Copyright © 2002 Pearson Education, Inc.

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:$myList[0] = "baseball";

Variable Name

Subscript

8 Copyright © 2002 Pearson Education, Inc.

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

9 Copyright © 2002 Pearson Education, Inc.

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.

@students = ('Johnson', 'Jones', 'Jackson', 'Jefferson' );

Comma separateeach list item.

List variablenames start

with "@" sign.

Enclose lists inparenthesis

10 Copyright © 2002 Pearson Education, Inc.

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.

11 Copyright © 2002 Pearson Education, Inc.

A Complete List Example Program

1. #!/usr/bin/perl2. 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

12 Copyright © 2002 Pearson Education, Inc.

Would Output The Following ...

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

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

14 Copyright © 2002 Pearson Education, Inc.

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

$#my_list

List variablename is @my_list

has ranger operator$#my_list.

Range operatorstarts with

'$' followed by '#'

15 Copyright © 2002 Pearson Education, Inc.

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.

16 Copyright © 2002 Pearson Education, Inc.

Using Range Operator for list length

1. #!/usr/bin/perl2. 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;

17 Copyright © 2002 Pearson Education, Inc.

Would Output The Following ...

18 Copyright © 2002 Pearson Education, Inc.

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;

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 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 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 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 Copyright © 2002 Pearson Education, Inc.

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

24 Copyright © 2002 Pearson Education, Inc.

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

25 Copyright © 2002 Pearson Education, Inc.

Extracting Multiple List Values

In a similar fashion, you can use a list variable as 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.

26 Copyright © 2002 Pearson Education, Inc.

Example Multiple Arguments

1. #!/usr/bin/perl2. 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;

27 Copyright © 2002 Pearson Education, Inc.

Would Output The Following ...

28 Copyright © 2002 Pearson Education, Inc.

Lists of Lists (or multidimensional lists)

Some data are best represented by a list of lists

PartNumber

Part Name NumberAvailable

Price

AC1000 Hammer 122 12AC1001 Wrench 344 5AC1002 Hand Saw 150 10

@Inventory = ([ 'AC1000', 'Hammer', 122, 12.50 ],[ 'AC1001', 'Wrench', 344, 5.50 ],[ 'AC1002', 'Hand Saw', 150, 10.00]

);

Regular parenthesis on outside.

A regular listvariable name

Each row is comma separated andenclosed in square brackets.

29 Copyright © 2002 Pearson Education, Inc.

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

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]”;

This would output

122, AC1000, 15

31 Copyright © 2002 Pearson Education, Inc.

A Complete Example ...

Suppose the following HTML code creates radio buttons and sets CGI variable item (0-3)

The output is sent to http://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

32 Copyright © 2002 Pearson Education, Inc.

Receiving CGI/Perl Program

1. #!/usr/bin/perl2. use CGI ':standard';3. print header, start_html('Inventory Answer');4. # Inventory: PartNO, Item, Num In Stock, Price5. $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 Copyright © 2002 Pearson Education, Inc.

Would Output The Following ...

34 Copyright © 2002 Pearson Education, Inc.

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

35 Copyright © 2002 Pearson Education, Inc.

Advantages of Using Loops

$max = 0; $max = 0; $i=0;if ( $grades[0] > $max ) { while ( $i < 4 ) { $max = $grades[0]; if ( $grades[$i] > $max ) {} if ( $grades[1] > $max ) { $max = $grades[$i];

$max = $grades[1]; }} if ( $grades[2] > $max ) { $i = $i + 1;

$max = $grades[2]; }} if ( $grades[3] > $max ) {

$max = $grades[3];}

Each time through looplook at different list element.

Without looping must have a separate"if" statement for every list element.

36 Copyright © 2002 Pearson Education, Inc.

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.

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)

for ( $i = 0; $i < $max; $i++ ) {

Set of statements to repeat}

Initializationexpression. Sets theinitial value of "$i"

Loop end condition.

Iteration expression.Increment $i each

loop iteration

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 Copyright © 2002 Pearson Education, Inc.

Consider the following program

1. #!/usr/bin/perl2. 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;

40 Copyright © 2002 Pearson Education, Inc.

Would Output The Following ...

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

foreach $item ( @items_array ) {

Set of statements to repeat}

A loop scalar value.It receives the next list elementeach loop iteration.

Repeat the loop once forevery element in the listvariable.

42 Copyright © 2002 Pearson Education, Inc.

A For Each Example Program

1. #!/usr/bin/perl2. 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. }

43 Copyright © 2002 Pearson Education, Inc.

Would Output The Following ...

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.

while ( $ctr < $max ) {

Set of statements to repeat}

Repeat as longas the conditionaltest is true.

Conditionenclosed in parenthesis

45 Copyright © 2002 Pearson Education, Inc.

Consider The Following ...1. #!/usr/bin/perl2. 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" );

46 Copyright © 2002 Pearson Education, Inc.

Would Output The Following ...

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

do { Set of statements to repeat

} until ( $x < 100 )

Repeat until thiscondition is true.

The "do"word startsthe loop

48 Copyright © 2002 Pearson Education, Inc.

Example Program

1. #!/usr/bin/perl2. 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" );

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

For example, while ( $x > $max && $found ne ‘TRUE’ )

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 Copyright © 2002 Pearson Education, Inc.

Consider the following ...

1. #!/usr/bin/perl2. 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 Copyright © 2002 Pearson Education, Inc.

Would Output The Following ...

53 Copyright © 2002 Pearson Education, Inc.

Summary

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.

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

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 Copyright © 2002 Pearson Education, Inc.

Summary

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.

top related