Introduction to Programming the WWW I

84
Introduction to Programming the WWW I CMSC 10100-1 Summer 2004 Lecture 10

description

Introduction to Programming the WWW I. CMSC 10100-1 Summer 2004 Lecture 10. Today’s Topics. Perl data types and variables. Review: Perl Data Types. Scalars The simplest kind of data Perl can work with Either a string or number (integer, real, etc) Arrays of scalars - PowerPoint PPT Presentation

Transcript of Introduction to Programming the WWW I

Introduction to Programming the WWW I

Introduction to Programming the WWW I

CMSC 10100-1

Summer 2004

Lecture 10

2

Today’s TopicsToday’s Topics

• Perl data types and variables

3

Review: Perl Data TypesReview: Perl Data Types

• Scalars The simplest kind of data Perl can work with Either a string or number (integer, real, etc)

• Arrays of scalars An ordered sequence of scalars

• Associate arrays of scalars (hash) A set of key/value pairs where the key is a

text string to help to access the value

4

Review: Perl VariablesReview: Perl Variables

• Variables are containers to store and access data in computer memory Variable names are not change in program The stored data usually changes during execution

• Three Variables in Perl Scalar variables - hold a singular item such as a

number (for example, 1, 1239.12, or –123) or a string (for example, “apple,” “ John Smith,” or “address”)

Array variables - hold a set of items Hash variables – hold a set of key/value pairs

5

Review: Scalar Variable and Assignment

Review: Scalar Variable and Assignment

• A scalar variable in Perl is always preceeded by the $ sign

• Place the variable’s name on the left side of an equals sign (=) and the value on the right side of the equals sign

• The following Perl statements use two variables: $x and $months

$x = 3; $months = 12;

Name of variable. Variable's new value

6

$X = 60; $Weeks = 4; $X = $Weeks;

• Assigns 4 to $X and $Weeks.

• Note: Perl variables are case sensitive $x and $X are considered different

variable names.

Review: Assigning New Values to Variables

Review: Assigning New Values to Variables

7

Selecting Variable Names Selecting Variable Names

• Perl variable rules

Perl variable names must have a dollar sign ($) as the first character.

The second character must be a letter or an underscore character

Less than 251 characters

Examples:

• Valid: $baseball, $_sum, $X, $Numb_of_bricks, $num_houses, and $counter1

• Not Valid: $123go, $1counter, and counter

8

Variables and the print Variables and the print

• Place a variable name inside the double quotes of the print statement to print out the value. E.g.,

print “The value of x= $x”;

1. #!/usr/bin/perl2. print “Content-type: text/html\n\n”;3. $x = 3;4. $y = 5;5. print “The value of x is $x. ”;6. print “The value of y= $y.”;

Assign 3 to $xAssign 5 to $y

9

Would Output The Following:Would Output The Following:

10

Basics of Perl Functions Basics of Perl Functions

• Perl includes built-in functions that provide powerful additional capabilities to enhance your programs

Work much like operators, except that most (but not all) accept one or more arguments (I.e., input values into functions).

function_name (argument1, argument2, argument3);

Comma separate each inputargument to function.

Name of the function.

Usually enclose arguments in parentheses.

11

The print FunctionThe print Function

• You can enclose output in parentheses or not

• When use double quotation marks, Perl outputs the value of any variables. For example,

$x = 10;print ("Mom, please send $x dollars");

• Output the following message:

Mom, please send 10 dollars

12

More on print()More on print()

• If want to output the actual variable name (and not its value), then use single quotation marks

$x = 10;print('Mom, please send $x dollars');

• Would output the following message:

Mom, please send $x dollars

13

Still More on print ()Still More on print ()

• Support multiple arguments separated by comma

Example:

$x=5;print('Send $bucks', " need $x. No make that ",

5*$x); Outputs:

Send $bucks need 5. No make that 25

14

String Variables String Variables

• Variables can hold numerical or character string data For example, to hold customer names,

addresses, product names, and descriptions. $letters=”abc”;

$fruit=”apple”;

Assign “abc”

Assign “apple”

Enclose in double quotes

15

String Variables String Variables

• The use of double quotes allows you to use other variables as part of the definition of a variable $my_stomach='full';

$full_sentence="My stomach feels $my_stomach.";

print "$full_sentence"; The value of $my_stomach is used as part of the $full_sentence

variable

16

Quotation MarksQuotation Marks

• Double quotation marks (“ “) Allow variable interpolation and escape sequences

• Variable Interpolation: any variable within double quotes will be replaced by its value when the string is printed or assigned to another variable

• Escape Sequences: Special characters in Perl: “ ‘ # $ @ %

• Not treated as characters if included in double quotes• Can be turned to characters if preceeded by a \ (backslash)

Other backslash interpretations (Johnson pp. 62)• \n – new line \t – tab

• Double quotes examples

17

Quotation MarksQuotation Marks

• Single quotation marks (‘ ‘) Marks are strictest form of quotes Everything between single quotes will be

printed literally How to print a single quote (‘) inside of a

single quotation marks?• Use backslash preceeding it

Single quotes examples

18

Perl OperatorsPerl Operators

• Different versions of the operators for numbers and strings

• Categories: Arithmetic operators Assignment operators Increment/decrement operators concatenate operator and repeat operator Numeric comparison operators String comparison operators Logical operators

19

Arithmetic OperatorsArithmetic OperatorsOperator Effect Example Result

+ Adds two items $x = 2 + 2; $x is assigned 4

- Subtraction $y = 3;$y = $y – 1;

$y is assigned 2

/ Division $y = 14 / 2; $y is assigned 7

* Multiplication $z = 4;$y = $z * 4;

$y is assigned 16

** Exponent $y = 2;$z = 4 ** $y;

$z is assign 16

% Remainder $y = 14 % 3; $y is assigned 2

20

Example ProgramExample Program

1. #!/usr/local/bin/perl2. print “Content-type: text/plain\n\n”;3. $cubed = 3 ** 3; 4. $onemore = $cubed + 1;5. $cubed = $cubed + $onemore;6. $remain = $onemore % 3;7. print “The value of cubed is $cubed onemore= $onemore ”;

8. print “The value of remain= $remain”;

Assign 27 to $cubedAssign 55 to $cubed

$remain is remainder of 28 / 3 or 1

21

Would Output The Following ...Would Output The Following ...

22

Writing Complex ExpressionsWriting Complex Expressions

• Operator precedence rules define the order in which the operators are evaluated

• For example, consider the following expression:

$x = 5 + 2 * 6; $x could = 42 or 17 depending on evaluation

order

23

Perl Precedence RulesPerl Precedence Rules

1. Operators within parentheses

2. Exponential operators

3. Multiplication and division operators

4. Addition and subtraction operatorsConsider the following

$X = 100 – 3 ** 2 * 2; $Y = 100 – ((3 ** 2) * 2);$Z = 100 – ( 3 ** (2 * 2) );

Evaluates to 82

Evaluates to 19

24

Review: Generating HTML with Perl Script

Review: Generating HTML with Perl Script

• Use MIME type text/html instead of text/plainprint “Content-type: text/html\n\n”;

• Add HTML codes in print()print “<HTML> <HEAD> <TITLE> Example </TITLE></HEAD>”;

Can use single quotes when output some HTML tags:

print ‘<FONT COLOR=”BLUE”>’;

Can use backslash (“\”) to signal that double quotation marks themselves should be output:

print “<FONT COLOR=\”$color\”>”;

25

Variables with HTML Output - IIVariables with HTML Output - II

1. #!/usr/local/bin/perl

2. print “Content-type: text/html\n\n”;

3. print “<HTML> <HEAD> <TITLE> Example </TITLE></HEAD>”;

4. print “<BODY> <FONT COLOR=BLUE SIZE=5>”;

5. $num_week = 8;

6. $total_day = $num_week * 7;

7. $num_months = $num_week / 4;

8. print “Number of days are $total_day </FONT>”;

9. print “<HR>The total number of months=$num_months”;

10. print “</BODY></HTML>”;

Assign 28Assign 2

Set bluefont, size 5

Horizontalrule followed by black font.

26

Would Output The Following ...Would Output The Following ...

Run in Perl Builder

27

Assignment OperatorsAssignment Operators

• Use the = sign as an assignment operator to assign values to a variable Variable = value;

• Precede the = sign with the arithmetic operators $revenue+=10; is equal to $revenue=$revenue+10;

28

Assignment OperatorsAssignment Operators

Operator Function

= Normal Assignment

+= Add and Assign

-= Subtract and Assign

*= Multiply and Assign

/= Divide and Assign

%= Modulus and Assign

**= Exponent and Assign

29

Increment/DecrementIncrement/Decrement

Operator Function

++ Increment (Add 1)

-- Decrement (Subtract 1)• ++ and -- can be added before or after a variable

and will be evaluated differently• Example 1:

$revenue=5; $total= ++$revenue + 10;

• Example 1:$revenue=5; $total= $revenue++ + 10;

$revenue = 6$total=16

$total = 15$revenue=6

30

String Operations String Operations

• String variables have their own operations. You cannot add, subtract, divide, or multiply string

variables.

• The concatenate operator joins two strings together and takes the form of a period (“.”).

• The repeat operator is used when you want to repeat a string a specified number of times

31

Concatentate Operator Concatentate Operator

• Joins two strings together (Uses period “.”)$FirstName = “Bull”;$LastName = “and Bear”;$FullName1 = $FirstName . $LastName;$FullName2 = $FirstName . “ “ . $LastName; print “FullName1=$FullName1 and

Fullname2=$FullName2”;

• Would output the following: FullName1=Bulland Bear and FullName2=Bull and Bear• Note … can use Double Quotation marks

$Fullname2 = “$FirstName $LastName”;

Same as $Fullname2 = $FirstName . “ “ . $LastName;

Single Quotation will treat the variable literally

32

Repeat Operator Repeat Operator

• Used to repeat a string a number of times. Specified by the following sequence:

$varname x 3

• For example,

$score = “Goal!”;$lots_of_scores = $score x 3;print “lots_of_scores=$lots_of_scores”;

• Would output the following:

lots_of_scores=Goal!Goal!Goal!

Repeat string value3 times.

33

A Full Program Example ...A Full Program Example ...

1. #!/usr/local/bin/perl2. print "Content-type: text/html\n\n";3. print "<HTML> <HEAD><TITLE> String Example</TITLE></HEAD>";

4. print "<BODY>";5. $first = "John";6. $last = "Smith";7. $name = $first . $last;8. $triple = $name x 3;9. print "<BR> name=$name";10.print "<BR> triple = $triple";

11. print "</BODY></HTML>";

Concatenate

Repeat

34

Would Output The Following ...Would Output The Following ...

Run in Perl Builder

35

Conditional StatementsConditional Statements

• Conditional statements enable programs to test for certain variable values and then react differently

• Use conditionals in real life: Get on Interstate 90 East at Elm Street and go east toward the city. If you encounter construction delays at mile marker 10, get off the expressway at this exit and take Roosevelt Road all the way into the city. Otherwise, stay on I-90 until you reach the city.

36

Conditional StatementsConditional Statements

• Perl supports 3 conditional clauses:

An if statement • specifies a test condition and set of statements to execute

when a test condition is true.

An elsif clause used with an if statement • specifies an additional test condition to check when the

previous test conditions are false.

An else clause is used with an if statement and possibly an elsif clause

• specifies a set of statements to execute when one or more test conditions are false.

37

The if StatementThe if Statement

• Uses a test condition and set of statements to execute when the test condition is true.

A test condition uses a test expression enclosed in parentheses within an if statement.

When the test expression evaluates to true, then one or more additional statements within the required curly brackets ({ … }) are executed.

if ( $aver > 69 ) { $Grade="Pass"; print "Grade=$Grade";}print "Your average was $aver";

Statement(s) to executeregardless of test condition.

Execute these statementswhen $aver is greater than 69.

38

Numerical Test OperatorsNumerical Test Operators

Numerical Test

Operator

Effect Example Result

== Equal to if ($x == 6){ $x = $y + 1; $y = $x + 1; }

Execute the second and third statements if the value of $x is equal to 6.

!= Not equal to if ($x != $y) { $x = 5 + 1; }

Execute the second statement if the value of $x is not equal to the value of $y.

< Less than if ($x < 100) { $y = 5; }

Execute the second statement if the value of $x is less than 100.

> Greater than if ($x > 51) { print “OK”; }

Execute the second statement if the value of $x is greater than 51.

>= Greater than or equal

if (16 >= $x) { print “x=$x”; }

Execute the second statement if 16 is greater than or equal to the value of $x.

<= Less than or equal to

if ($x <= $y) { print “y=$y”; print “x=$x”; }

Execute the second and third statements if the value of $x is less than or equal to the value of $y.

39

A Sample Conditional ProgramA Sample Conditional Program

1. #!/usr/bin/perl2. print "Content-type: text/html\n\n";3. print "<HTML> <HEAD><TITLE> String Example </TITLE></HEAD>";

4. print "<BODY>";5. $grade = 92; 6. if ( $grade > 89 ) { 7. print “<FONT COLOR=BLUE> Hey you got an A.</FONT><BR> ”; 8. } 9. print “Your actual score was $grade”;

10. print “</BODY></HTML>”;

40

Would Output The Following ...Would Output The Following ...

Run in Perl Builder

41

String Test Operators String Test Operators

• Perl supports a set of string test operators that are based on ASCII code values.

ASCII code is a standard, numerical representation of characters.

Every letter, number, and symbol translates into a code number.

• “A” is ASCII code 65, and “a” is ASCII code 97.

• Numbers are lower ASCII code values than letters, uppercase letters lower than lowercase letters.

• Letters and numbers are coded in order, so that the character “a” is less than “b”, “C” is less than “D”, and “1” is less than “9”.

42

String Test OperatorsString Test OperatorsTest Operator Effect Example Result

eq Equal to $name=”Nelson”; if ($name eq “Nelson”){ print “Got Nelson”; }

Prints Got Nelson because $name is equal to “Nelson”.

ne Not equal to $alert=”Smoke”; if ( $alert ne “fire” ){ print “$alert NE fire”; $ok = $ok + 1; }

Prints Smoke NE fire and then executes fourth line, because $alert is not equal to “fire”.

lt Less than if ( “auto” lt “car” ) { print “Before car”; }

Prints Before car because “auto” is less than “car”.

gt Greater than if (“Jones” gt “Smith” ){ print “After Smith”; }

Prints nothing because “Jones” is not greater than “Smith”.

ge Greater than or

equal to

if ( “WSOX” ge “Cubs” ){ print “Sox Win”; }

Prints Sox Win because “WSOX” is greater than or equal to “Cubs”.

le Less than or

equal to

$Name = “Bob”; if (“Bob” le $Name ) { print “Got Bob”; }

Prints Got Bob because “Bob” is less than or equal to $Name.

43

The elsif Clause The elsif Clause

• Specifies an additional test condition to check when all previous test conditions are false. Used only with if statement When its condition is true, gives one or more

statements to execute $found = 0; if ( $name eq "Joe" ) {

print "Got Name of Joe";$found = 1;

} elsif ( $name eq "Jane" ) {

print "Got Name of Jane";$found = 1;

} print "Name=$name and found=$found\n";

Execute these wheni f condi t i on i s

true.Execute these wheni ts condi t i on i strue but previ ous

i s f al se.

Executedregardl ess of theprevi oustest condi t i ons.

44

The elsif Clause The elsif Clause

1. #!/usr/local/bin/perl 2. print “Content-type: text/html\n\n”; 3. $grade = 92; 4. if ( $grade >= 100 ) { 5. print “Illegal Grade > 100 ”; 6. } 7. elsif ( $grade < 0 ) { 8. print “illegal grade < 0 ”; 9. } 10.elsif ( $grade > 89 ){ 11. print “Hey you got an A ”; 12.}13. print “Your actual grade was $grade”;

Run in Perl Builder

45

The else Clause The else Clause

• Specifies a set of statements to execute when all other test conditions in an if block are false.

It must be used with at least one if statement, (can also be used with an if followed by one or several elsif statements.

if ( $name eq "Joe" ) {print "Got Name of Joe";

} elsif ( $name eq "Jane" ) {

print "Got Name of Jane"; } else {

print "Could not validate Name=$name"; }

One or more statements to executewhen test condition is true.

One or more statements to executewhen its test condition is true but the previous testcondition is false.

One or more statements to executewhen the previous test condition(s) are false.

46

Using An else ClauseUsing An else Clause

1.#!/usr/local/bin/perl 2.print “Content-type: text/html\n\n”; 3.$grade = 92; 4.if ( $grade >= 100 ) { 5. print “Illegal Grade > 100”; 6.} 7.elsif ( $grade < 0 ) { 8. print “illegal grade < 0”; 9.} 10.elsif ( $grade > 89 ){ 11. print “Hey you got an A”; 12.} 13.else { 14. print “Sorry you did not get an A”;

15.}

47

Using unlessUsing unless

• The unless condition checks for a certain condition and executes it every time unless the condition is true. Sort of like the opposite of the if statement

• Example: unless ($gas_money == 10) {

print "You need exact change. 10 bucks please.";

}

48

List DataList 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

49

Why use array variable?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

50

Creating List VariablesCreating 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’

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

Comma separateeach l i st i tem.

Array vari abl enames start

wi th "@" si gn.

Encl ose l i sts i nparenthesi s

51

Creating Array Variables Of ScalarsCreating 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.

52

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

Variable Name

Subscript

53

Referencing Array Items - IIReferencing 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

54

Changing Items In An Array Variable

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.

55

A Complete Array Example Program

A Complete Array Example Program

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

56

Outputting the Entire Array VariableOutputting 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

57

Getting the Number in an Array VariableGetting 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];

$#my_list

List variablename is @my_list

has ranger operator$#my_list.

Range operatorstarts with

'$' followed by '#'

$#grades=3

58

Using Range Operator for list lengthUsing 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.

59

A Better Way to Get List LengthA 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;

60

Adding and Removing List Items

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

61

Adding and Removing List ItemsAdding 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

62

Adding and Removing List ItemsAdding 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 followingdayOff= Friday workWeek=Monday Tuesday Wednesday Thursday

63

Adding and Removing List ItemsAdding 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

64

Extracting Multiple List Values 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

65

Lists of Lists (or multidimensional lists)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

@I nventory = ([ ' AC1000' , ' Hammer' , 122, 12. 50 ] ,[ ' AC1001' , ' Wrench' , 344, 5. 50 ] ,[ ' AC1002' , ' Hand Saw' , 150, 10. 00]

) ;

Regul ar parenthesi s on outsi de.

A regul ar arrayvari abl e name

Each row i s comma separated andencl osed i n square brackets.

66

Accessing Individual ItemsAccessing 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

67

A Partial Example ...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

68

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

69

Advantages of Using LoopsAdvantages 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.

70

The Perl Looping ConstructsThe 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

71

The for loopThe 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}

Ini ti al i zati onexpressi on. Sets thei ni ti al val ue of "$i "

Loop test condi ti on.

I terati on expressi on.Increment $i each

l oop i terati on

72

3 Parts to the for Loop3 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. )

73

for loop examplefor loop example

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

74

The foreach Loop 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”.

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.

75

foreach Exampleforeach Example

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

8. $found=1;9. last;10. }11.}12.if (!$found){13. print “Could not find the number/n”;14. }

The last statement willForce an exit of the loop

Run in Perl Builder

76

Would Output The Following ...Would Output The Following ...

77

The while Loop 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

78

Consider The Following ...Consider The Following ...

Calculation of sum from 1 to 5

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

79

Hw3 discussionHw3 discussion

• Problem3: using while loop to read input from command line# while the program is running, it will return # to this point and wait for inputwhile (<>){

$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

chomp() is a built-in functionto remove the end-of-line character of a string

80

The until Loop 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 unti l thi scondi ti on i s true.

The "do"word startsthe l oop

81

Example Program Example Program

Calculation of sum from 1 to 5

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

Run in Perl Builder

82

Logical Operators(Compound Conditionals)

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’

83

Some Basic Logical Operators 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 falseif ( !($FLAG == 0) )

84

Consider the following ...Consider the following ...1. #!/usr/local/bin/perl2. @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