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

55
1 Copyright © 2002 Pearson Education, Inc.

Upload: jordan-young

Post on 26-Mar-2015

216 views

Category:

Documents


1 download

TRANSCRIPT

Page 1: 1 Copyright © 2002 Pearson Education, Inc.. 2 Chapter 5 List Variables and Loops

1 Copyright © 2002 Pearson Education, Inc.

Page 2: 1 Copyright © 2002 Pearson Education, Inc.. 2 Chapter 5 List Variables and Loops

2 Copyright © 2002 Pearson Education, Inc.

Chapter 5List Variables and Loops

Page 3: 1 Copyright © 2002 Pearson Education, Inc.. 2 Chapter 5 List 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

Page 4: 1 Copyright © 2002 Pearson Education, Inc.. 2 Chapter 5 List Variables and Loops

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.

Page 5: 1 Copyright © 2002 Pearson Education, Inc.. 2 Chapter 5 List Variables and Loops

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

Page 6: 1 Copyright © 2002 Pearson Education, Inc.. 2 Chapter 5 List Variables and Loops

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.

Page 7: 1 Copyright © 2002 Pearson Education, Inc.. 2 Chapter 5 List Variables and Loops

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

Page 8: 1 Copyright © 2002 Pearson Education, Inc.. 2 Chapter 5 List Variables and Loops

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

Page 9: 1 Copyright © 2002 Pearson Education, Inc.. 2 Chapter 5 List Variables and Loops

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

Page 10: 1 Copyright © 2002 Pearson Education, Inc.. 2 Chapter 5 List Variables and Loops

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.

Page 11: 1 Copyright © 2002 Pearson Education, Inc.. 2 Chapter 5 List Variables and Loops

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

Page 12: 1 Copyright © 2002 Pearson Education, Inc.. 2 Chapter 5 List Variables and Loops

12 Copyright © 2002 Pearson Education, Inc.

Would Output The Following ...

Page 13: 1 Copyright © 2002 Pearson Education, Inc.. 2 Chapter 5 List Variables and Loops

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

Page 14: 1 Copyright © 2002 Pearson Education, Inc.. 2 Chapter 5 List Variables and Loops

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 '#'

Page 15: 1 Copyright © 2002 Pearson Education, Inc.. 2 Chapter 5 List Variables and Loops

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.

Page 16: 1 Copyright © 2002 Pearson Education, Inc.. 2 Chapter 5 List Variables and Loops

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;

Page 17: 1 Copyright © 2002 Pearson Education, Inc.. 2 Chapter 5 List Variables and Loops

17 Copyright © 2002 Pearson Education, Inc.

Would Output The Following ...

Page 18: 1 Copyright © 2002 Pearson Education, Inc.. 2 Chapter 5 List Variables and Loops

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;

Page 19: 1 Copyright © 2002 Pearson Education, Inc.. 2 Chapter 5 List Variables and Loops

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

Page 20: 1 Copyright © 2002 Pearson Education, Inc.. 2 Chapter 5 List Variables and Loops

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

Page 21: 1 Copyright © 2002 Pearson Education, Inc.. 2 Chapter 5 List Variables and Loops

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

Page 22: 1 Copyright © 2002 Pearson Education, Inc.. 2 Chapter 5 List Variables and Loops

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

Page 23: 1 Copyright © 2002 Pearson Education, Inc.. 2 Chapter 5 List Variables and Loops

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

Page 24: 1 Copyright © 2002 Pearson Education, Inc.. 2 Chapter 5 List Variables and Loops

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

Page 25: 1 Copyright © 2002 Pearson Education, Inc.. 2 Chapter 5 List Variables and Loops

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.

Page 26: 1 Copyright © 2002 Pearson Education, Inc.. 2 Chapter 5 List Variables and Loops

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;

Page 27: 1 Copyright © 2002 Pearson Education, Inc.. 2 Chapter 5 List Variables and Loops

27 Copyright © 2002 Pearson Education, Inc.

Would Output The Following ...

Page 28: 1 Copyright © 2002 Pearson Education, Inc.. 2 Chapter 5 List Variables and Loops

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.

Page 29: 1 Copyright © 2002 Pearson Education, Inc.. 2 Chapter 5 List Variables and Loops

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

Page 30: 1 Copyright © 2002 Pearson Education, Inc.. 2 Chapter 5 List Variables and Loops

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

Page 31: 1 Copyright © 2002 Pearson Education, Inc.. 2 Chapter 5 List Variables and Loops

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

Page 32: 1 Copyright © 2002 Pearson Education, Inc.. 2 Chapter 5 List Variables and Loops

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;

Page 33: 1 Copyright © 2002 Pearson Education, Inc.. 2 Chapter 5 List Variables and Loops

33 Copyright © 2002 Pearson Education, Inc.

Would Output The Following ...

Page 34: 1 Copyright © 2002 Pearson Education, Inc.. 2 Chapter 5 List Variables and Loops

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

Page 35: 1 Copyright © 2002 Pearson Education, Inc.. 2 Chapter 5 List Variables and Loops

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.

Page 36: 1 Copyright © 2002 Pearson Education, Inc.. 2 Chapter 5 List Variables and Loops

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.

Page 37: 1 Copyright © 2002 Pearson Education, Inc.. 2 Chapter 5 List Variables and Loops

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

Page 38: 1 Copyright © 2002 Pearson Education, Inc.. 2 Chapter 5 List Variables and Loops

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

Page 39: 1 Copyright © 2002 Pearson Education, Inc.. 2 Chapter 5 List Variables and Loops

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;

Page 40: 1 Copyright © 2002 Pearson Education, Inc.. 2 Chapter 5 List Variables and Loops

40 Copyright © 2002 Pearson Education, Inc.

Would Output The Following ...

Page 41: 1 Copyright © 2002 Pearson Education, Inc.. 2 Chapter 5 List Variables and Loops

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.

Page 42: 1 Copyright © 2002 Pearson Education, Inc.. 2 Chapter 5 List Variables and Loops

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

Page 43: 1 Copyright © 2002 Pearson Education, Inc.. 2 Chapter 5 List Variables and Loops

43 Copyright © 2002 Pearson Education, Inc.

Would Output The Following ...

Page 44: 1 Copyright © 2002 Pearson Education, Inc.. 2 Chapter 5 List Variables and Loops

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

Page 45: 1 Copyright © 2002 Pearson Education, Inc.. 2 Chapter 5 List Variables and Loops

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" );

Page 46: 1 Copyright © 2002 Pearson Education, Inc.. 2 Chapter 5 List Variables and Loops

46 Copyright © 2002 Pearson Education, Inc.

Would Output The Following ...

Page 47: 1 Copyright © 2002 Pearson Education, Inc.. 2 Chapter 5 List Variables and Loops

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

Page 48: 1 Copyright © 2002 Pearson Education, Inc.. 2 Chapter 5 List Variables and Loops

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" );

Page 49: 1 Copyright © 2002 Pearson Education, Inc.. 2 Chapter 5 List Variables and Loops

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

Page 50: 1 Copyright © 2002 Pearson Education, Inc.. 2 Chapter 5 List Variables and Loops

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 )

Page 51: 1 Copyright © 2002 Pearson Education, Inc.. 2 Chapter 5 List Variables and Loops

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;

Page 52: 1 Copyright © 2002 Pearson Education, Inc.. 2 Chapter 5 List Variables and Loops

52 Copyright © 2002 Pearson Education, Inc.

Would Output The Following ...

Page 53: 1 Copyright © 2002 Pearson Education, Inc.. 2 Chapter 5 List Variables and Loops

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.

Page 54: 1 Copyright © 2002 Pearson Education, Inc.. 2 Chapter 5 List Variables and Loops

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.

Page 55: 1 Copyright © 2002 Pearson Education, Inc.. 2 Chapter 5 List Variables and Loops

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.