Introduction to Programming the WWW I CMSC 10100-1 Winter 2004 Lecture 8.

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.
Objectives Using functions to organize PHP code
Functions & Arrays. Functions Functions offer the ability for programmers to group together program code that performs specific task or function into.
PHP Functions and Control Structures. 2 Defining Functions Functions are groups of statements that you can execute as a single unit Function definitions.
Perl Arrays and Lists Learning Objectives: 1. To understand the format and the declaration of Arrays & Lists in Perl 2. To distinguish the difference between.
Scripting Languages Chapter 6 I/O Basics. Input from STDIN We’ve been doing so with $line = chomp($line); Same as chomp($line= ); line input op gives.
1 Controlling Script Flow! David Lash Chapter 3 Conditional Statements.
Chapter 4 Functions and Control Structures PHP Programming with MySQL.
Engineering H192 - Computer Programming The Ohio State University Gateway Engineering Education Coalition Lect 11P. 1Winter Quarter Arrays Lecture 11.
Perl File I/O and Arrays. File I/O Perl allows to open a file to read, write, or append As well as pipe input or output to another program. —We get to.
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.
Perl Tutorial Presented by Pradeepsunder. Why PERL ???  Practical extraction and report language  Similar to shell script but lot easier and more powerful.
Array Processing Simple Program Design Third Edition A Step-by-Step Approach 7.
Chapter 2 - Algorithms and Design
Introduction to Programming the WWW I CMSC Summer 2004 Lecture 11.
CPTG286K Programming - Perl Chapter 3: Arrays and List Data.
Control Structures Week Introduction -Representation of the theory and principles of structured programming. Demonstration of for, while,do…whil.
1 DATA STRUCTURES: LISTS. 2 LISTS ARE USED TO WORK WITH A GROUP OF VALUES IN AN ORGANIZED MANNER. A SERIES OF MEMORY LOCATIONS CAN BE DIRECTLY REFERENCED.
 2008 Pearson Education, Inc. All rights reserved JavaScript: Arrays.
Introduction to Programming the WWW I CMSC Summer 2004 Lecture 10.
Meet Perl, Part 2 Flow of Control and I/O. Perl Statements Lots of different ways to write similar statements –Can make your code look more like natural.
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.
Copyright © 2003 Pearson Education, Inc. Slide 5-1 The Web Wizard’s Guide to PHP by David Lash.
Chapter 2 Functions and Control Structures PHP Programming with MySQL 2 nd Edition.
1 Module 3 Conditional Statements. Objectives  Conditional test statements to compare numerical and string data values  Looping statements to repeat.
Built-in Data Structures in Python An Introduction.
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.
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
CS161 Topic #16 1 Today in CS161 Lecture #16 Prepare for the Final Reviewing all Topics this term Variables If Statements Loops (do while, while, for)
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 8 Lists and Tuples.
Introduction to Matlab Module #4 Page 1 Introduction to Matlab Module #4 – Programming Topics 1.Programming Basics (fprintf, standard input) 2.Relational.
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.
Topic 4:Subroutines CSE2395/CSE3395 Perl Programming Learning Perl 3rd edition chapter 4, pages 56-72, Programming Perl 3rd edition pages 80-83,
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)
Slide 5-1 CHAPTER 5 Using Arrays for List Data Objectives To understand the benefits of using arrays in PHP To learn how to create and use sequential.
1 Printing in Python Every program needs to do some output This is usually to the screen (shell window) Later we’ll see graphics windows and external files.
 2001 Prentice Hall, Inc. All rights reserved. Chapter 7 - Introduction to Common Gateway Interface (CGI) Outline 7.1Introduction 7.2A Simple HTTP Transaction.
 2008 Pearson Education, Inc. All rights reserved. 1 Arrays and Vectors.
Perl Variables: Array Web Programming1. Review: Perl Variables Scalar ► e.g. $var1 = “Mary”; $var2= 1; ► holds number, character, string Array ► e.g.
Think Possibility 1 Iterative Constructs ITERATION / LOOPS C provides three loop structures: the for-loop, the while-loop, and the do-while-loop. Each.
Engineering H192 - Computer Programming The Ohio State University Gateway Engineering Education Coalition Lect 11P. 1Winter Quarter Arrays Lecture 11.
LISTS and TUPLES. Topics Sequences Introduction to Lists List Slicing Finding Items in Lists with the in Operator List Methods and Useful Built-in Functions.
Perl for Bioinformatics Part 2 Stuart Brown NYU School of Medicine.
CSI605 perl. Perl Facts Perl = Pathologically Eclectic Rubbish Lister Perl is highly portable across many different platforms and operating systems Perl.
Copyright © 2003 Pearson Education, Inc. Slide 5-1 The Web Wizard’s Guide to PHP by David Lash.
Arrays and Lists. What is an Array? Arrays are linear data structures whose elements are referenced with subscripts. Just about all programming languages.
Perl Chapter 3 Conditional statements. Control Expressions Control expressions – interpreted as T/F (evaluated as strings or numbers) – simple, relational,
Copyright © 2003 Pearson Education, Inc. Slide 3-1 The Web Wizard’s Guide to PHP by David A. Lash.
CSC 4630 Perl 3 adapted from R. E. Beck. Problem But we worked on it first: Input: Read from a text file named in a command line argument Output: List.
For Friday Read No quiz Program 6 due. Program 6 Any questions?
 2008 Pearson Education, Inc. All rights reserved JavaScript: Arrays.
Copyright © 2013 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with Programming Logic & Design Third Edition by Tony Gaddis.
FILES AND EXCEPTIONS Topics Introduction to File Input and Output Using Loops to Process Files Processing Records Exceptions.
Chapter 17 Arrays Perl to denote an array, for = (10, 20, 30, 50); Array subscripts are number from 0. Array elements require scalar.
REPETITION CONTROL STRUCTURE
Chapter 5 - Control Structures: Part 2
Miscellaneous Items Loop control, block labels, unless/until, backwards syntax for “if” statements, split, join, substring, length, logical operators,
While Loops BIS1523 – Lecture 12.
Perl Variables: Array Web Programming.
Control Structures: for & while Loops
The Web Wizard’s Guide to PHP
Topics Sequences Introduction to Lists List Slicing
Topics Sequences Introduction to Lists List Slicing
Presentation transcript:

Introduction to Programming the WWW I CMSC Winter 2004 Lecture 8

2 Today’s Topics Variables and operators (lec7) Conditional statements (lec7) List (array) and hash Loop statements

3 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

4 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

5 Creating List Variables Suppose wanted to create an array variable to hold 4 student names: Creates array with values ‘Johnson’, ‘Jones’, ‘Jackson’, and ‘Jefferson’

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

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

8 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

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

10 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

11 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

12 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

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

14 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 : 

15 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

16 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

17 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

18 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

19 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

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

21 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

22 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

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

24 Advantages of Using Loops

25 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

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

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

28 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

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

30 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

31 Would Output The Following...

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

33 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

34 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

35 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

36 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

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

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

39 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