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

Slides:



Advertisements
Similar presentations
1 Copyright © 2002 Pearson Education, Inc.. 2 Chapter 5 List Variables and Loops.
Advertisements

Arrays A list is an ordered collection of scalars. An array is a variable that holds a list. Arrays have a minimum size of 0 and a very large maximum size.
Lecture 2 Introduction to C Programming
Introduction to C Programming
 2000 Prentice Hall, Inc. All rights reserved. Chapter 2 - Introduction to C Programming Outline 2.1Introduction 2.2A Simple C Program: Printing a Line.
Introduction to C Programming
1 *Copyright © 2002 Pearson Education, Inc.. 2 Web Wizard’s Guide to CGI/Perl David Lash Chapter 3 Perl Basics.
1 Controlling Script Flow! David Lash Chapter 3 Conditional Statements.
 2008 Pearson Education, Inc. All rights reserved JavaScript: Introduction to Scripting.
Scalar Variables Start the file with: #! /usr/bin/perl –w No spaces or newlines before the the #! “#!” is sometimes called a “shebang”. It is a signal.
 2007 Pearson Education, Inc. All rights reserved Introduction to C Programming.
JavaScript, Fourth Edition
JavaScript, Third Edition
Introduction to C Programming
 2008 Pearson Education, Inc. All rights reserved JavaScript: Control Statements II.
String Escape Sequences
Programming Concepts MIT - AITI. Variables l A variable is a name associated with a piece of data l Variables allow you to store and manipulate data in.
11 Chapter 4 LOOPS AND FILES. 22 THE INCREMENT AND DECREMENT OPERATORS To increment a variable means to increase its value by one. To decrement a variable.
Slide 6a-1 CHAPTER 6 Matching Patterns: Using Regular expressions to match patterns.
Copyright © 2003 Pearson Education, Inc. Slide 5-1 The Web Wizard’s Guide to PHP by David Lash.
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 2 Input, Processing, and Output.
2440: 211 Interactive Web Programming Expressions & Operators.
Introduction to Java Applications Part II. In this chapter you will learn:  Different data types( Primitive data types).  How to declare variables?
Input, Output, and Processing
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 2 Chapter 2 - Introduction to C Programming.
Introduction to C Programming Angela Chih-Wei Tang ( 唐 之 瑋 ) Department of Communication Engineering National Central University JhongLi, Taiwan 2010 Fall.
Slide 3-1 CHAPTER 3 Conditional Statements Objectives To learn to use conditional test statements to compare numerical and string data values To learn.
Copyright © 2010 Certification Partners, LLC -- All Rights Reserved Perl Specialist.
1 Module 3 Conditional Statements. Objectives  Conditional test statements to compare numerical and string data values  Looping statements to repeat.
Lecture 2: Introduction to C Programming. OBJECTIVES In this lecture you will learn:  To use simple input and output statements.  The fundamental data.
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 2 Input, Processing, and Output.
Lecture 2: Introduction to C Programming. OBJECTIVES In this lecture you will learn:  To use simple input and output statements.  The fundamental data.
CSC 107 – Programming For Science. The Week’s Goal.
Chapter 9: Perl Programming Practical Extraction and Report Language Some materials are taken from Sams Teach Yourself Perl 5 in 21 Days, Second Edition.
Selection Relational Expressions A condition or logical expression is an expression that can only take the values true or false. A.
 2008 Pearson Education, Inc. All rights reserved JavaScript: Control Statements I.
Prof. Alfred J Bird, Ph.D., NBCT Office – McCormick 3rd floor 607 Office Hours – Tuesday and.
Computer Programming for Biologists Class 3 Nov 13 th, 2014 Karsten Hokamp
ECA 225 Applied Interactive Programming1 ECA 225 Applied Online Programming basics.
Internet & World Wide Web How to Program, 5/e © by Pearson Education, Inc. All Rights Reserved.
Perl Tutorial. Why PERL ??? Practical extraction and report language Similar to shell script but lot easier and more powerful Easy availablity All details.
Copyright © 2003 ProsoftTraining. All rights reserved. Perl Fundamentals.
More Perl Data Types Scalar: it may be a number, a character string, or a reference to another data type. -the sigil $ is used to denote a scalar(or reference)
 2008 Pearson Education, Inc. All rights reserved JavaScript: Introduction to Scripting.
Programming in Java (COP 2250) Lecture 4 Chengyong Yang Fall, 2005.
CSC 1010 Programming for All Lecture 3 Useful Python Elements for Designing Programs Some material based on material from Marty Stepp, Instructor, University.
Basic Variables & Operators Web Programming1. Review: Perl Basics Syntax ► Comments: start with # (ignored by Perl) ► Statements: ends with ; (performed.
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Fluency with Information Technology Third Edition by Lawrence Snyder Chapter.
Internet & World Wide Web How to Program, 5/e © by Pearson Education, Inc. All Rights Reserved.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Chapter 2 - Introduction to C Programming Outline.
Introduction to Java Applications Part II. In this chapter you will learn:  Different data types( Primitive data types).  How to declare variables?
Introduction to Programming the WWW I CMSC Winter 2004 Lecture 7.
 2007 Pearson Education, Inc. All rights reserved. A Simple C Program 1 /* ************************************************* *** Program: hello_world.
Internet & World Wide Web How to Program, 5/e © by Pearson Education, Inc. All Rights Reserved.
Copyright © 2003 Pearson Education, Inc. Slide 3-1 The Web Wizard’s Guide to PHP by David A. Lash.
PHP Tutorial. What is PHP PHP is a server scripting language, and a powerful tool for making dynamic and interactive Web pages.
REEM ALMOTIRI Information Technology Department Majmaah University.
OPERATORS IN C CHAPTER 3. Expressions can be built up from literals, variables and operators. The operators define how the variables and literals in the.
Introduction to Programming the WWW I CMSC Winter 2004 Lecture 8.
1 Lecture 2 - Introduction to C Programming Outline 2.1Introduction 2.2A Simple C Program: Printing a Line of Text 2.3Another Simple C Program: Adding.
Topics Designing a Program Input, Processing, and Output
Chapter 6 JavaScript: Introduction to Scripting
Chapter 5 - Control Structures: Part 2
Introduction to C++ Programming
Chapter 8 JavaScript: Control Statements, Part 2
The Web Wizard’s Guide to PHP
Topics Designing a Program Input, Processing, and Output
Topics Designing a Program Input, Processing, and Output
Chapter 8 JavaScript: Control Statements, Part 2
Presentation transcript:

Introduction to Programming the WWW I CMSC Summer 2004 Lecture 10

2 Today’s Topics Perl data types and variables

3 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  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 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, , 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 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

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

7 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 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/perl 2. 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 $x Assign 5 to $y

9 Would Output The Following:

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

11 The 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() 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 () 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 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 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 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 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 Single quotes examples

18 Perl 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 Operators

20 Example Program 1. #!/usr/local/bin/perl 2. 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 $cubed Assign 55 to $cubed $remain is remainder of 28 / 3 or 1

21 Would Output The Following...

22 Writing Complex Expressions Operator precedence rules define the order in which the operators are evaluated For example, consider the following expression:  $x = * 6;  $x could = 42 or 17 depending on evaluation order

23 Perl Precedence Rules 1. Operators within parentheses 2. Exponential operators 3. Multiplication and division operators 4. Addition and subtraction operators Consider 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 Use MIME type text/html instead of text/plain print “Content-type: text/html\n\n”; Add HTML codes in print() print “ Example ”;  Can use single quotes when output some HTML tags: print ‘ ’;  Can use backslash (“ \ ”) to signal that double quotation marks themselves should be output: print “ ”;

25 Variables with HTML Output - II 1. #!/usr/local/bin/perl 2. print “Content-type: text/html\n\n”; 3. print “ Example ”; 4. print “ ”; 5. $num_week = 8; 6. $total_day = $num_week * 7; 7. $num_months = $num_week / 4; 8. print “Number of days are $total_day ”; 9. print “ The total number of months=$num_months”; 10. print “ ”; Assign 28 Assign 2 Set blue font, size 5 Horizontal rule followed by black font.

26 Would Output The Following...  Run in Perl Builder Run in Perl Builder

27 Assignment 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 Operators OperatorFunction =Normal Assignment +=Add and Assign -=Subtract and Assign *=Multiply and Assign /=Divide and Assign %=Modulus and Assign **=Exponent and Assign

29 Increment/Decrement OperatorFunction ++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 ; $revenue = 6 $total=16 $total = 15 $revenue=6

30 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 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 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 value 3 times.

33 A Full Program Example #!/usr/local/bin/perl 2. print "Content-type: text/html\n\n"; 3. print " String Example "; 4. print " "; 5. $first = "John"; 6. $last = "Smith"; 7. $name = $first. $last; 8. $triple = $name x 3; 9. print " name=$name"; 10.print " triple = $triple"; 11. print " "; Concatenate Repeat

34 Would Output The Following...  Run in Perl Builder Run in Perl Builder

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

38 Numerical Test Operators

39 A Sample Conditional Program 1. #!/usr/bin/perl 2. print "Content-type: text/html\n\n"; 3. print " String Example "; 4. print " "; 5. $grade = 92; 6. if ( $grade > 89 ) { 7. print “ Hey you got an A. ”; 8. } 9. print “Your actual score was $grade”; 10. print “ ”;

40 Would Output The Following...  Run in Perl Builder Run in Perl Builder

41 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. ASCII code  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 Operators

43 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

44 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 Run in Perl Builder

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

46 Using 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 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 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 symbol

49 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 Variables Suppose wanted to create an array variable to hold 4 student names: Creates array with values ‘Johnson’, ‘Jones’, ‘Jackson’, and ‘Jefferson’

51 Creating Array Variables Of Scalars Suppose wanted to create an array variable to hold 4 student grades (numerical = ( 66, 75, 85, 80 ); Creates array with values 66, 75, 85, 80.

52 Referencing 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:

53 Referencing Array Items - II Subscripts can be whole numbers, another variable, or even expressions enclosed within the square brackets. Consider the following example: = (“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 Change values in an array variable and use them in expressions like other scalar variables. For example: = ( 75, 65, 85, 90);  $scores[3] = 95;  $average = ( $scores[0] + $scores[1] +  $scores[2] + $scores[3] ) / 4; The third line sets $average equal to ( ) / 4, that is, to 80.

55 A Complete Array Example Program 1. #!/usr/local/bin/perl = ('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 Run in Perl Builder

56 Outputting the Entire Array Variable Output all of the elements of an array variable by using the array variable with print For = ('Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday' ); print "My work week Would output the following:  My work week is Monday Tuesday Wednesday Thursday Friday

57 Getting the Number in an Array Variable Use Range operator to find last element of list For = ( 66, 75, 85, 80 ); $last_one = $grades[$#grades]; $#grades=3

58 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 = (‘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 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 : 

60 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 = (‘Monday’, ‘Tuesday’, ‘Wednesday’,‘Thursday’, ‘Friday’ ); $dayOff = print "dayOff=  Would output the following: dayOff= Monday workWeek=Tuesday Wednesday Thursday Friday

61 Adding and Removing List Items  unshift() adds an element to the beginning of the list For = (‘Monday’, ’Tuesday’, ’Wednesday’, ’Thursday’, ’Friday’ ); “Sunday”); print “workWeek is now  would output the following: workWeek is now =Sunday Monday Tuesday Wednesday Thursday Friday

62 Adding 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 = (“Monday”, “Tuesday”, “Wednesday”, “Thursday”, “Friday” ); $dayOff =  Would output the following dayOff= Friday workWeek=Monday Tuesday Wednesday Thursday

63 Adding and Removing List Items  push() adds an element to the end of the list For = (‘Monday’, ‘Tuesday’, ‘Wednesday’, ‘Thursday’, ‘Friday’ ); ‘Saturday’); print “workWeek is now  would output the following: workWeek is now =Monday Tuesday Wednesday Thursday Friday Saturday

64 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 = ( 'hot dogs’, 'ketchup', 'lettuce', 2, 3 ]; print The output of this code is essentials=lettuce celery

65 Lists of Lists (or multidimensional lists) Some data are best represented by a list of lists

66 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

67 A Partial = ( [ 'AC1000', 'Hammer', 122, ], [ '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 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 Loops

70 The 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 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)

72 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-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 example 1. #!/usr/local/bin/perl 2. 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 Run in Perl Builder

74 The foreach Loop The foreach loop is typically used to repeat a set of statements for each item in an array = (“A”, “B”, “C”);  Then $item would “A” then “B” then “C”.

75 foreach Example 1. #!/usr/local/bin/perl = ( 3, 6, 9 ); 3.$uinput = 6; 4. $ctr=0; $found = 0; 5. foreach $item ) { 6. $ctr=$ctr+1; 7. if ( $item == $uinput ) { print "Number $item. Item found was number $ctr "; 8. $found=1; 9. last; 10. } 11. } 12.if (!$found){ 13. print “Could not find the number/n”; 14.} The last statement will Force an exit of the loop  Run in Perl Builder Run in Perl Builder

76 Would Output The Following...

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

78 Consider The Following... Calculation of sum from 1 to 5 1. #!/usr/local/bin/perl 2. 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 Run in Perl Builder

79 Hw3 discussion Problem3: using while loop to read input from command line Problem3 # while the program is running, it will return # to this point and wait for input while (<>){ $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 Flowchartmy example chomp() is a built-in function to remove the end-of-line character of a string

80 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

81 Example Program Calculation of sum from 1 to 5 1. #!/usr/local/bin/perl 2. 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 must end with a ;  Run in Perl Builder Run in Perl Builder

82 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 && —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 false if ( !($FLAG == 0) )

84 Consider the following #!/usr/local/bin/perl = (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 Run in Perl Builder