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

Slides:



Advertisements
Similar presentations
Introduction to C Programming
Advertisements

Modular Programming With Functions
Computer Programming for Biologists Class 9 Dec 4 th, 2014 Karsten Hokamp
Copyright © 2003 Pearson Education, Inc. Slide 6b-1 The Web Wizard’s Guide to PHP by David Lash.
CS 330 Programming Languages 10 / 14 / 2008 Instructor: Michael Eckmann.
CS 898N – Advanced World Wide Web Technologies Lecture 8: PERL Chin-Chih Chang
 2006 Pearson Education, Inc. All rights reserved Introduction to Classes and Objects.
CS 330 Programming Languages 10 / 11 / 2007 Instructor: Michael Eckmann.
PERL Part 3 1.Subroutines 2.Pattern matching and regular expressions.
Linux+ Guide to Linux Certification, Second Edition
Chapter 5: Loops and Files.
Introduction to PERL Part 4 (1) Working with Files (2)CGI Security.
ASP.NET Programming with C# and SQL Server First 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.
Computer Programming for Biologists Class 2 Oct 31 st, 2014 Karsten Hokamp
Intermediate PHP (2) File Input/Output & User Defined Functions.
IE 212: Computational Methods for Industrial Engineering
Introduction to Python
Operator Precedence First the contents of all parentheses are evaluated beginning with the innermost set of parenthesis. Second all multiplications, divisions,
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.
IPC144 Introduction to Programming Using C Week 1 – Lesson 2
Introduction to Programming the WWW I CMSC Summer 2004 Lecture 11.
Linux+ Guide to Linux Certification, Third Edition
Linux+ Guide to Linux Certification Chapter Eight Working with the BASH Shell.
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
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.
Chapter 9 I/O Streams and Data Files
CS 330 Programming Languages 10 / 07 / 2008 Instructor: Michael Eckmann.
Introduction to Perl Yupu Liang cbio at MSKCC
7 1 User-Defined Functions CGI/Perl Programming By Diane Zak.
Chapter 9: Perl (continue) Advanced Perl Programming Some materials are taken from Sams Teach Yourself Perl 5 in 21 Days, Second Edition.
Introduction to Unix – CS 21
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
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.
Topic 4:Subroutines CSE2395/CSE3395 Perl Programming Learning Perl 3rd edition chapter 4, pages 56-72, Programming Perl 3rd edition pages 80-83,
Introduction to Perl October 4, 2004 Class Meeting 7 * Notes on Perl by Lenwood Heath, Virginia Tech © 2004.
 2008 Pearson Education, Inc. All rights reserved JavaScript: Introduction to Scripting.
Introduction to Python Dr. José M. Reyes Álamo. 2 Three Rules of Programming Rule 1: Think before you program Rule 2: A program is a human-readable set.
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.
Python Let’s get started!.
Perl Variables: Array Web Programming1. Review: Perl Variables Scalar ► e.g. $var1 = “Mary”; $var2= 1; ► holds number, character, string Array ► e.g.
 2008 Pearson Education, Inc. All rights reserved Introduction to Classes and Objects.
Linux+ Guide to Linux Certification, Second Edition
Learners Support Publications Working with Files.
Perl for Bioinformatics Part 2 Stuart Brown NYU School of Medicine.
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.
Perl Subroutines User Input Perl on linux Forks and Pipes.
Shell Scripting September 27, 2004 Class Meeting 6, Part II * Notes adapted by Lenwood Heath from previous work by other members of the CS faculty at Virginia.
Linux Administration Working with the BASH Shell.
ITM 3521 ITM 352 Functions. ITM 3522 Functions  A function is a named block of code (i.e. within {}'s) that performs a specific set of statements  It.
FILES AND EXCEPTIONS Topics Introduction to File Input and Output Using Loops to Process Files Processing Records Exceptions.
Built-In Functions. Notations For each function, I will give its name and prototype. –prototype = number and type of arguments ARRAY means an actual named.
BIL 104E Introduction to Scientific and Engineering Computing Lecture 4.
String and Lists Dr. José M. Reyes Álamo.
Shell Scripting March 1st, 2004 Class Meeting 7.
Topics Introduction to File Input and Output
String and Lists Dr. José M. Reyes Álamo.
Topics Introduction to File Input and Output
Internet Programming Work with Files in PHP
Topics Introduction to File Input and Output
Presentation transcript:

Introduction to Programming the WWW I CMSC Summer 2004 Lecture 12

2 Today’s Topics Working with files Subroutines(functions)

3 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

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

5 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

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

7 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

8 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

9 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

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

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

12 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

13 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.\n"; } close (INFILE); …

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

15 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: $!”;

16 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”;

17 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

18 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

19 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

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

21 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

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

23 Subroutines (functions) Subroutines provide a way for programmers to group a set of statements, set them aside, and turn them into mini-programs within a larger program. These mini-programs can be executed several times from different places in the overall program Library functions vs. User-defined functions

24 Subroutine Advantages Smaller overall program size. Can place statements executed several times into a subroutine and just call them when needed. Programs that are easier to understand and change. Subroutines can make complex and long programs easier to understand and change. (e.g., Divide into logical sections). Reusable program sections. You might find that some subroutines are useful to other programs. (E.g, Common page footer). common page footer.

25 More Library Functions abs() – return the absolute value of a number rand() – generate a random number from 0 to the input number  Use int() with rand()  Example: localtime() – used with time() function to determine the current date and time  ($sec, $min, $hr, $day, $mon, $yr, $wkday, $DayNumOfYr, $TZ ) = localtime(time());  Example:

26 String Functions changing case  lc(), lcfirst(), uc(), ucfirst() length and substrings  length() Example: $len = length(“Hello”);  substr(string, index, length) Example: $part = substr(“Hello”, 2, 2); chomp() and chop()  chop() will remove the last char of the string and return it Example: $char = chop (“Hello”);

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

28 Define Your Own Subroutines You can create a subroutine by placing a group of statements into the following format: sub subroutine_name { set of statements } sub subroutine_name ($parameter1, $parameter2,…) { set of statements } For example a outputTableRow subroutine sub outputTableRow { print ‘ One Two ’; }

29 Rules to Execute a Function Function name with parentheses  myFunction( argument1, argument2,... ) Prepended function symbol, &, function name with parentheses:  &myFunction( argument1, argument2,... )  &outputTableRow(); or &outputTableRow; Parentheses may be omitted in certain conditions:  myFunction, &myFunction, or myFunction parameter Perl's Calling Conventions of Functions  /winter/ /02/perl/perl_function_calls.html /winter/ /02/perl/perl_function_calls.html

30 Subroutine Example Program #!/usr/local/bin/perl print "Content-type: text/html\n\n"; print qq+ Subroutine Example Here is simple table +; &outputTableRow(); &outputTableRow(); &outputTableRow(); print qq+ +; sub outputTableRow { print ' One Two '; }

31 Would Output The Following …

32 Passing Arguments to Subroutines Generalize a subroutine using input variables (called parameters or arguments). &outputTableRow( ‘A First Cell’, ‘A Second Cell’ ); Use a special array to access arguments: $_[0] as the variable name for the first argument, $_[0] would be set to ‘A First Cell’ and $_[1] as the variable name for the second argument, $_[1] would be set to ‘A Second Cell’ : … $_[n] as the variable name for the n th argument.

33 Full Subroutine Example #!/usr/local/bin/perl print "Content-type: text/html\n\n"; print qq+ Subroutine Example Here is simple table +; for ( $i=1; $i<=3; $i++ ) { &outputTableRow( "Row $i Col 1", "Row $i Col 2"); } print qq+ +; sub outputTableRow { print “ $_[0] $_[1] ”; }

34 Would Output The Following...

35 Subroutine Argument $foo=42; print sub something{ $_[0]=13; $_[2]=4; print } will print $foo=42; print sub something{ $copy[0]=13; $copy[2]=4; print } will print Make a private copy of the arguments to keep the original values intact

36 Getting the Number of Arguments There are at least two different ways …  The range operator is set to the last element in a list variable. Therefore, within a subroutine the number of arguments is: $numargs = $#_ + 1;  Second, you can use variable directly. For example, $numargs

37 Returning Values Subroutines can return values (can return list) to the calling program.  $result = sqrt(144); To Return a value within a subroutine: Stops the subroutine execution and return the specified value to the calling program.

38 Example Subroutine Return Value $bigger = &calc_bigger( $num1, $num2 ); 1. sub calc_bigger { 2. # PURPOSE: returns the bigger of 2 numbers 3. # ARGUMENTS $[0] – 1 st number, $_[1] – 2 nd number 4. if ( $[0] > $[1] ) { 5. return( $[0] ); 6. }else { 7. return( $[1] ); 8. } 9.}

39 Scope Global, lexical(private) and dynamic scopes  Default function variables are global  A variable can be made lexical(private) by preceding with the keyword my my $myVar = 23.65;  A variable can be made dynamic by preceding with the keyword local local %myHash = (California => "Sacramento", Wisconsin => "Madison"); Examples:

40 It is sometimes useful to place sub-routines in external separate files to promote their reuse  Other programs can use them without creating separate copies To store in external file: 1.Move subroutine lines to a new file. For example, move outputTableRow sub outputTableRow { print ' One Two '; } Using Subroutines in External Files

41 2.Place a 1 at the end of the new file. This step provides a return value of 1, which helps Perl recognize that the subroutine executed successfully. 3.Name the subroutine file. Usually, this file has a.lib suffix, which indicates that it is a library file of subroutines. For example, you might call the file startdoc.lib. Using Subroutines in External Files

42 4.Place the file in the same directory as the program file. (Can reside in another directory but For now assume in same.) 5.Include an additional require line in the calling program. Before a program can use the subroutine library file, it must add a line that indicates where to look for that file. This line has the following format:  require ‘library_filename’; Using Subroutines in External Files

43 Example External Subroutine File Content of file 'htmlhelper1.lib‘: 1. sub outputTableRow { 2. # PURPOSE: outputs a table row with 2 cols 3. # ARGUMENTS: uses $_[0] for first col 4. # : uses $_[1] for second col 5. print " $_[0] $_[1] "; 6. } 7. sub specialLine { 8. # PURPOSE: Output a line with varible color: 9. # ARGUMENTS: $_[0] is the line to output 10. # : $_[1] is the line color. 11. print " $_[0] "; 12. } 13. 1

44 Example Calling Program 1. #!/usr/local/bin/perl 2. print "Content-type: text/html\n\n"; 3. require 'htmlhelper1.lib'; 4. …; 5. &specialLine('Here is a simple table', 'RED'); 6. print ' '; 7. print ' Num Num Cubed '; 8. for ( $i=0; $i<3; $i++ ) { 9. &outputTableRow($i, $i**3); 10. } 11. …;

45 Would Output The Following...