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

Slides:



Advertisements
Similar presentations
1 Copyright © 2002 Pearson Education, Inc.. 2 Chapter 6 Managing End-User Sessions.
Advertisements

Java Script Session1 INTRODUCTION.
Copyright © 2003 Pearson Education, Inc. Slide 6b-1 The Web Wizard’s Guide to PHP by David Lash.
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
Programming with Alice Computing Institute for K-12 Teachers Summer 2011 Workshop.
CS 898N – Advanced World Wide Web Technologies Lecture 8: PERL Chin-Chih Chang
1 Controlling Script Flow! David Lash Chapter 3 Conditional Statements.
 2008 Pearson Education, Inc. All rights reserved JavaScript: Introduction to Scripting.
Linux+ Guide to Linux Certification, Second Edition
Chapter 5: Loops and Files.
 2007 Pearson Education, Inc. All rights reserved Introduction to C Programming.
Introduction to PERL Part 4 (1) Working with Files (2)CGI Security.
Guide To UNIX Using Linux Third Edition
Introduction to C Programming
 2004 Prentice Hall, Inc. All rights reserved. Chapter 25 – Perl and CGI (Common Gateway Interface) Outline 25.1 Introduction 25.2 Perl 25.3 String Processing.
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.
Introduction to Programming the WWW I CMSC Summer 2004 Lecture 12.
Week 7 Working with the BASH Shell. Objectives  Redirect the input and output of a command  Identify and manipulate common shell environment variables.
Introduction to Programming the WWW I CMSC Summer 2004 Lecture 6.
Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display. A Concise Introduction to MATLAB ® William J. Palm III.
Linux+ Guide to Linux Certification, Third Edition
Linux Operations and Administration
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.
1 Module 3 Conditional Statements. Objectives  Conditional test statements to compare numerical and string data values  Looping statements to repeat.
Introduction to Perl Yupu Liang cbio at MSKCC
Chapter 9: Perl (continue) Advanced Perl Programming Some materials are taken from Sams Teach Yourself Perl 5 in 21 Days, Second Edition.
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
Storing and Retrieving Data
Introduction to Programming the WWW I CMSC Winter 2003.
5 1 Data Files CGI/Perl Programming By Diane Zak.
Open Source Server Side Scripting ECA 236 Open Source Server Side Scripting Files & Directories.
Perl Tutorial. Why PERL ??? Practical extraction and report language Similar to shell script but lot easier and more powerful Easy availablity All details.
Verification & Validation. Batch processing In a batch processing system, documents such as sales orders are collected into batches of typically 50 documents.
Copyright © 2003 ProsoftTraining. All rights reserved. Perl Fundamentals.
Lecture 26: Reusable Methods: Enviable Sloth. Creating Function M-files User defined functions are stored as M- files To use them, they must be in the.
 2008 Pearson Education, Inc. All rights reserved JavaScript: Introduction to Scripting.
Introduction to Perl. What is Perl Perl is an interpreted language. This means you run it through an interpreter, not a compiler. Similar to shell script.
Loops and Files. 5.1 The Increment and Decrement Operators.
 2001 Prentice Hall, Inc. All rights reserved. Chapter 7 - Introduction to Common Gateway Interface (CGI) Outline 7.1Introduction 7.2A Simple HTTP Transaction.
8 Chapter Eight Server-side Scripts. 8 Chapter Objectives Create dynamic Web pages that retrieve and display database data using Active Server Pages Process.
 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.
Perl for Bioinformatics Part 2 Stuart Brown NYU School of Medicine.
1 CSC160 Chapter 1: Introduction to JavaScript Chapter 2: Placing JavaScript in an HTML File.
1 Copyright © 2002 Pearson Education, Inc.. 2 Chapter 6 Hashes (Associative Arrays), Environmental Variables and Functions.
Introduction to Programming the WWW I CMSC Winter 2003 Lecture 17.
Copyright © 2003 Pearson Education, Inc. Slide 3-1 The Web Wizard’s Guide to PHP by David A. Lash.
CS Class 04 Topics  Selection statement – IF  Expressions  More practice writing simple C++ programs Announcements  Read pages for next.
Learning Javascript From Mr Saem
4 - Conditional Control Structures CHAPTER 4. Introduction A Program is usually not limited to a linear sequence of instructions. In real life, a programme.
1 Agenda  Unit 7: Introduction to Programming Using JavaScript T. Jumana Abu Shmais – AOU - Riyadh.
Linux Administration Working with the BASH Shell.
FILES AND EXCEPTIONS Topics Introduction to File Input and Output Using Loops to Process Files Processing Records Exceptions.
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.
Intro to PHP & Variables
While Loops BIS1523 – Lecture 12.
Arrays, For loop While loop Do while loop
Topics Introduction to File Input and Output
T. Jumana Abu Shmais – AOU - Riyadh
File I/O in C Lecture 7 Narrator: Lecture 7: File I/O in C.
Flowcharts and Pseudo Code
Topics Introduction to File Input and Output
Presentation transcript:

Introduction to Programming the WWW I CMSC Summer 2004 Lecture 11

2 Today’s Topics Looping statement Hash data type Working with files

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

4 Advantages of Using Loops

5 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

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

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

8 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

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

10 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

11 Would Output The Following...

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

13 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

14 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

15 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

16 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

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

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

19 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

20 Hash Lists (or associated arrays) Items not stored sequentially but stored in pairs of values  the first item the key, the second the data  The key is used to look up or provide a cross- reference to the data value.  Instead of using sequential subscripts to refer to data in a list, you use keys.

21 Advantages of Hash Lists Need to cross-reference one piece of data with another.  Perl supports some convenient functions that use hash lists for this purpose. (E.g,. You cross reference a part number with a product description.) Concerned about the access time required for looking up data.  Hash lists provide quicker access to cross-referenced data. E.g, have a large list of product numbers and product description, cost, and size, pictures).

22 Using Hash Lists General Format to define a hash list: Alternate syntax %months = ( "Jan" => 31, "Feb" => 28, "Mar" => 31, "Apr" => 30, "May" => 31, "Jun" => 30, "Jul" => 31, "Aug" => 31, "Sep" => 30, "Oct" => 31,"Nov" => 30, "Dec" => 31 );

23 Accessing Hash List Item When access an individual item, use the following syntax: Note: You Cannot Fetch Keys by Data Values. This is NOT valid : $mon = $months{ 28 };

24 Hash Keys and Values Access Functions The keys() function returns a list of all keys in the hash list %Inventory = ( 'Nuts', 33, 'Bolts', 55, 'Screws', = keys(%Inventory); print The values() function returns a list of all values Example, %Inventory = ( 'Nuts', 33, 'Bolts', 55, 'Screws', = values(%Inventory); print Perl outputs hash keys and values according to how they are stored internally. So, a possible output order: keyitems= Screws Bolts Nuts

25 Keys() & values() are often used to output the contents of a hash list. For example, % Inventory = ( 'Nuts', 33, 'Bolts', 55, 'Screws', 12); foreach $key ( keys (%Inventory) ) { print “Key=$key Value=$Inventory{$key} "; } The following is one possible output order: Item=Screws Value=12 Item=Bolts Value=55 Item=Nuts Value=33 Using keys() and values()

26 Changing a Hash Element You can change the value of a hash list item by giving it a new value in an assignment statement. For example, %Inventory = ( 'Nuts', 33, 'Bolts', 55, 'Screws', 12); $Inventory{‘Nuts’} = 34; This line changes the value of the value associated with Nuts to 34.

27 Adding a Hash Element You can add items to the hash list by assigning a new key a value. For example, %Inventory = ( 'Nuts', 33, 'Bolts', 55, 'Screws', 12); $Inventory{‘Nails’} = 23; These lines add the key Nails with a value of 23 to the hash list.

28 Deleting a Hash Element You can delete an item from the hash list by using the delete() function. For example, %Inventory = ( 'Nuts', 33, 'Bolts', 55, 'Screws', 12); delete $Inventory{‘Bolts’}; These lines delete the Bolts key and its value of 55 from the hash list.

29 Verifying an Element’s Existence Use the exists() function verifies if a particular key exists in the hash list.  It returns true ( or 1) if the key exists. (False if not). For example: %Inventory = ( 'Nuts', 33, 'Bolts', 55, 'Screws', 12); if ( exists( $Inventory{‘Nuts’} ) ) { print ( “Nuts are in the list” ); } else { print ( “No Nuts in this list” ); } This code outputs Nuts are in the list.

30 Environmental Hash Lists When your Perl program starts from a Web browser, a special environmental hash list is made available to it.  Comprises a hash list that describe the environment (state) when your program was called. (called the %ENV hash). Can be used just like any other hash lists. For example,

31 Some environmental variables HTTP_USER_AGENT. defines the browser name, browser version, and computer platform of the user who is starting your program.  For example, its value might be “Mozilla/4.7 [en] (Win 98, I)” for Netscape.  You may find this value useful if you need to output browser-specific HTML code.

32 Some Environmental Variables HTTP_ACCEPT_LANGUAGE - defines the language that the browser is using.  E.g., might be “en” for English for Netscape or “en- us” for English for Internet Explorer. REMOTE_ADDR - indicates the TCP/IP address of the computer that is accessing your site.  (ie., the physical network addresses of computers on the Internet —for example, )  May have value if log visitor information

33 Some environmental variables REMOTE_HOST - set to the domain name of the computer connecting to your Web site.  It is a logical name that maps to a TCP/IP address—for example,  It is empty if the Web server cannot translate the TCP/IP address into a domain name. Display all environmental variables 

34 Example: Checking Language #!/usr/local/bin/perl print "content-type: text/html\n\n"; print " \n \n"; print " Check Environment "; print " \n \n"; $lang=$ENV{'HTTP_ACCEPT_LANGUAGE'}; if ( $lang eq 'en' || $lang eq 'en-us' ) { print "Language=$ENV{'HTTP_ACCEPT_LANGUAGE'}"; print " Browser= $ENV{'HTTP_USER_AGENT'}"; }else { print 'Sorry I do not speak your language'; } print "\n \n ";

35 Printing Text Blocks In Perl there are easier ways to print out large blocks of code instead of line-by-line Solution 1: print <<"CodeBlock"; #some word(s) to indicate the beginning of a # block(no " " are needed) if it's a simple word.. CodeBlock #same word(s) to mark the end of block. #Notice no quotes or semicolon here! Solution 2: print qq+ #qq followed by some character not used in #the following text to start the block.. +; #the same character to mark the end of the block. #Notice semicolon #here! Examples : old_version solution1 solution2 old_versionsolution1solution2

36 Creating a Hash List of List Items Hash tables use a key to cross-reference the key with a list of values (instead of using simple key/value pairs). For example consider the following table

37 Creating Hash Tables Access items from a hash table much like you access a hash list:  $Inventory{‘AC1000’}[0] is ‘Hammer’,  $Inventory{‘AC1001’}[0] is ‘Wrench’,  $Inventory{‘AC1002’}[1] is 150.

38 Changing Hash Table Items Changing Hash table items: %Inventory = ( AC1000 => [ 'Hammer', 122, 12, 'hammer.gif'], AC1001 =>[ 'Wrench', 344, 5, 'wrench.gif'], AC1002 =>[ 'Hand Saw', 150, 10, 'saw.gif'] ); $numHammers = $Inventory{‘AC1000’}[1]; $Inventory{‘AC1001’}[1] = $Inventory{‘AC1001’}[1] + 1; $partName = $Inventory{‘AC1002’}[0]; print “$numHammers, $partName, $Inventory{‘AC1001’}[1]”; This code would output 122, Hand Saw, 345

39 Adding/Deleting Hash Table Items When you want to add a hash table row, you must specify a key and list of items.  For example, the following item adds an entry line to the %Inventory hash table %Inventory = ( AC1000 => [ 'Hammers', 122, 12, 'hammer.gif'], AC1001 => [ 'Wrenches', 344, 5, 'wrench.gif'], AC1002 => [ 'Hand Saws', 150, 10, 'saw.gif'] ); $Inventory{‘AC1003’} = [‘Screw Drivers’, 222, 3, ‘sdriver.gif’ ];

40 Because the exists() and delete() hash functions both work on a single key,specify them just as you did before  For example, the following code checks whether a key exists before deleting it: if ( exists $Inventory{‘AC1003’} ) { delete $Inventory{‘AC1003’}; } else { print “Sorry we do not have the key”; } Check if the record exists before you try to delete it. Adding/Deleting Hash Table Items

41 Working with Files So far programs cannot store data values in- between times when they are started.  Working with files enable programs to store data, which can then be used at some future time. Will describe ways to work with files in CGI/Perl programs, including  opening files,  closing files,  and reading from and writing to files

42 Using the open() Function Use to connect a program to a physical file on a Web server. It has the following format:  file handle - Starts with a letter or number—not with “ $ ”, ”, or “ % ”. (Specify in all capital letters. (By Perl convention.)  filename - name of file to connect to. If resides in the same file system directory then just specify the filename (and not the entire full file path).

43 More On open() function open() returns 1 (true) when it successfully opens and returns 0 (false) when this attempt fails. A common way to use open() $infile = “mydata.txt”; open (INFILE, $infile ) || die “Cannot open $infile: $!”; Execute die only when open fails Output system message Connect to mydata.txt. Perl special variable, containing the error string

44 Specifying Filenames So far need to keep file in same directory  You can specify a full directory path name for the file to be opened.

45 File Handles Use the file handle to refer to an opened file Combine with the file handle with the file input operator (“ <> ”) to read a file into your program Perl automatically opens 3 file handles upon starting a program  STDIN -- standard in, usually the keyboard Empty input operator (<>) is the same as  STDOUT -- standard out, usually the monitor screen print() function prints to STDOUT by default  STDERR -- standard error, usually the monitor screen

46 Using the File Handle to Read Files You can read all the content of a file into an array variable  Each line turns to an array item Or you can read the file line by line  Using the special variable of Perl, $_ The “mydata.txt” file used in the following 2 examples: Apples are red Bananas are yellow Carrots are orange Dates are brown

47 Reading File into Array $infile="mydata.txt"; open (INFILE, $infile ) || die "Cannot open $infile: = ; print $infile[0]; print $infile[2]; close (INFILE); Then the output of this program would be Apples are red Carrots are orange

48 Reading One Line At a Time Reading a very large file into the list consumes a lot of computer memory.  Better is to read one line at a time. For example the following would print each line of the input file. $infile=”mydata.txt”; open (INFILE, $infile ) || die “Cannot open $infile: $!”; while ( ) { $inline = $_; print $inline; } close (INFILE); Automatically set to the next input line.

49 Two String Functions split(/pattern/, string)  Search the string for occurrence of the pattern. it encounters one, it puts the string section before the pattern into an array and continues to search  Return the array  Example: (run in command line) join(“pattern”, array)  Taking an array or list of values and putting the into a single string separated by the pattern  Return the string  Reverse of split()  Example:

50 Working with split() Function Data usually stored as records in a file  Each line is a record  Multiple record members usually separated by a certain delimiter The record in the following input file “part.txt” has the format part_no:part_name:stock_number:price AC1000:Hammers:122:12 AC1001:Wrenches:344:5 AC1002:Hand Saws:150:10 AC1003:Screw Drivers:222:3

51 Example Program … $infile="infile.txt"; open (INFILE, $infile )|| die "Cannot open $infile:$!"; while ( ) { $inline=$_; ($ptno, $ptname, $num, $price ) = split ( /:/, $inline ); print "We have $num $ptname ($ptno). "; print "The cost is $price dollars.", br; } close (INFILE); …

52 Using Data Files Do not store your data files in a location that is viewable by people over the Internet—  too much potential for tampering by people you do not know.  Make sure permissions are set correctly (644)

53 Open Modes Three open modes are commonly used to open a file:  read-only (default mode) To explicitly specify it, put the character < before the filename. open(INFILE, “<myfile.txt”) || die “Cannot open: $!” ;  write-only-overwrite: allows you to write to a file. If the file exists, it overwrites the existing file with the output of the program. To specify this mode, use > at the beginning of the filename used in the open() function. For example, open(INFILE, “>myfile.txt”) || die “Cannot open: $!”;

54 Open Modes(cont’d) write-only-append: allows you to write and append data to the end of a file.  If the file exists, it will write to the end of the existing file. Otherwise will create it.  To specify this mode, use >> before the filename in the open() function. open(OFILE, “>>myfile.txt”) || die “Cannot open: $!”; Example way to write to print OFILE “My program was here”;

55 Locking Before Writing If two programs try to write to the same file at the same time, can corrupt a file.  an unintelligible, usefully mixture of file contents  provides a flock() function that ensures only one Perl program at a time can write data. flock(OFILE, 2); Exclusive access to file. File handle. Change 2 to 8 To unlock the file

56 Example of flock() $outfile=">>/home/perlpgm/data/mydata.txt"; open (OFILE, $outfile ) || die "Cannot open $outfile: $!"; flock( OFILE, 2 ); print OFILE "AC1003:Screw Drivers:222:3\n"; close (OFILE); Appends the following to part.txt : AC1003:Screw Drivers:222:3

57 Reading and Writing Files #!/usr/bin/perl print "Content-type: text/html\n\n"; print qq+ My Page WELCOME TO MY SITE +; $ctfile="counter.txt"; open (CTFILE, "<". $ctfile ) || die "Cannot open $infile: = ; $count=$inline[0] + 1; close (CTFILE); open (CTFILE, ">$ctfile" ) || die "Cannot open $infile: $!"; flock (CTFILE, 2); print CTFILE "$count"; close (CTFILE); print qq+ You Are Visitor $count +; counter.txt permission must be RW

58 Read Directory Content Not much different from reading a file  Use opendir(), readdir(), and closedir() functions Example: $dir = "/home/hai/html/hw4/"; opendir(DIR, = readdir(DIR); foreach $entry print $entry. "\n"; } closedir(DIR);

59 File Test Example of Perl file testing functions:  -e $file :exists  -z $file : zero file  -s $file : non-zero file, returns size  -r $file : readable  -w $file : write-able  -x $file : executable  -f $file : plain file  -d $file : directory  -T $file : text file  -B $file : binary file  -M $file : age in days since modified  -A $file : age in days since last accessed man.html#ixABE

60 File = readdir(DIR); if (-d $entry ){ # test if it is a directory print $entry. " is a directory\n"; }elsif (-f $entry ){ # test if it is a file print $entry. " is a "; if (-T $entry ){ # test if it is a text file print "text file,"; }elsif (-B $entry ){ # test if it is a binary file print "binary file,"; }else { print "file of unknown format,"; } print " “. (-s $entry). " bytes\n"; # get the file size }