Presentation is loading. Please wait.

Presentation is loading. Please wait.

A Guide to Unix Using Linux Fourth Edition Chapter 9 Perl and CGI Programming.

Similar presentations


Presentation on theme: "A Guide to Unix Using Linux Fourth Edition Chapter 9 Perl and CGI Programming."— Presentation transcript:

1 A Guide to Unix Using Linux Fourth Edition Chapter 9 Perl and CGI Programming

2 A Guide to Unix Using Linux, Fourth Edition 2 Objectives Understand the basics of the Perl language Identify and use data types in Perl scripts Understand differences between the Awk program and Perl programming Access disk files in Perl

3 A Guide to Unix Using Linux, Fourth Edition 3 Objectives (continued) Use Perl to sort information Set up a simple HTML Web page Understand how Perl and CGI are used for creating Web pages

4 A Guide to Unix Using Linux, Fourth Edition 4 Introduction to Perl Perl: Practical Extraction and Report Language –Free script language –Runs on many operating systems Examples: UNIX, Linux, Windows, Mac OS X –Manipulates text, displays output, handles mathematical processes, and works with files –Generating reports –Used for Web programming –Released by Larry Wall in 1987 –Interpreted language Interpreter: /usr/bin/perl

5 A Guide to Unix Using Linux, Fourth Edition 5 Introduction to Perl (continued) #!/usr/bin/perl # Program name: example1.pl print("This is a simple\n"); print("Perl program.\n");

6 A Guide to Unix Using Linux, Fourth Edition 6 Introduction to Perl (continued) The following script uses a variable: Output: #!/usr/bin/perl # Program name: example2.pl $name = "Charlie"; print ("Greetings $name\n"); ~]$./example2.pl Greetings Charlie

7 A Guide to Unix Using Linux, Fourth Edition 7 Introduction to Perl (continued) #!/usr/bin/perl # Program name: example3.pl print ("Enter a number: "); $number = ; print ("You entered $number\n");

8 A Guide to Unix Using Linux, Fourth Edition 8 Introduction to Perl (continued) #!/usr/bin/perl # Program name: example4.pl print ("Enter a number: "); $number = ; if ($number == 10) { print ("That is the number I was thinking of.\n"); } else { print ("You entered $number\n"); }

9 A Guide to Unix Using Linux, Fourth Edition 9 Introduction to Perl (continued)

10 A Guide to Unix Using Linux, Fourth Edition 10 Introduction to Perl (continued)

11 A Guide to Unix Using Linux, Fourth Edition 11 Introduction to Perl (continued) #!/usr/bin/perl # Program name: example5.pl $my_name = "Ellen"; $your_name = "Charlie"; if ($my_name eq $your_name) { print ("Your name is the same as mine.\n"); } else { print ("Hello. My name is $my_name\n"); } Perl offers the if-else statement: Output: ~]$./example5.pl Hello. My name is Ellen

12 A Guide to Unix Using Linux, Fourth Edition 12 Introduction to Perl (continued) Perl provides standard arithmetic operators: Output: #!/usr/bin/perl # Program name: example6.pl $num1 = 10; $num2 = 50; $num3 = 12; $average = ($num1 + $num2 + $num3) / 3; print ("The average is $average\n"); ~]$./example6.pl The average is 24

13 A Guide to Unix Using Linux, Fourth Edition 13 Identifying Data Types In Perl, data can be represented in a variety of ways –Variables and constants –Scalars –Numbers –Strings –Arrays –Hashes

14 A Guide to Unix Using Linux, Fourth Edition 14 Variables and Constants Variables: symbolic names that represent values stored in memory –Examples: $x might hold the value 100 $name might hold the sequence of characters Charlie –Value can change while program runs Constants do not change value as the program runs –Written into the program code itself –Example: $num =

15 A Guide to Unix Using Linux, Fourth Edition 15 Scalars Scalar: simple variable that holds a number or string –Name begins with a $ Examples: – $x = 12; – $name = "Jill"; – $pay = ;

16 A Guide to Unix Using Linux, Fourth Edition 16 Numbers Numbers are stored inside the computer as: –Signed integers (e.g., 14321) –Double-precision, floating-point values (e.g., 56.85) Numeric literals are integers or floating-point values Perl uses underscore (_) to improve legibility: –Example: 5_456_678_901 –Only works within literal numbers specified in a program 0x used to express hexadecimal constants

17 A Guide to Unix Using Linux, Fourth Edition 17 Strings Strings are sequences of any types of characters Delimited by ‘’ or “” –Single-quoted strings are not subject to interpolation Except for \' and \\ –In double-quoted strings, variables are interpolated Backslash (\) used to ensure variable or control character is not interpolated

18 A Guide to Unix Using Linux, Fourth Edition 18 Strings (continued)

19 A Guide to Unix Using Linux, Fourth Edition 19 #!/usr/bin/perl # Program name: example7.pl print ("\\words\\separated\\by\\slashes\n"); print ("This is a \"quote\"\n"); print ("\Uupper case\n"); print ("\LLOWER CASE\n");

20 A Guide to Unix Using Linux, Fourth Edition 20 Arrays Arrays are variables that store an ordered list of scalar values –Elements are accessed with numeric subscripts Starting at zero –Elements are usually of the same data type An “at” sign precedes the name of an array when assigning it values $ character used when processing the individual elements

21 A Guide to Unix Using Linux, Fourth Edition 21 #!/usr/bin/perl # Program name: = ("dog", "cat", "parrot", "hamster" ); print ("My pets are:\n"); print ("$pets[0]\n"); print ("$pets[1]\n"); print ("$pets[2]\n"); print ("$pets[3]\n");

22 A Guide to Unix Using Linux, Fourth Edition 22 Hashes Hash: variable that represents a set of key/value pairs Hash variables are preceded by % when they are assigned values %animals = (’Tigers’, 10, ’Lions’, 20, ’Bears’, 30); %animals = (Tigers ==> 10, Lions ==> 20, Bears ==> 30); To refer to an element, use $ before the variable name followed by the key in {} $animals{’Bears’}

23 A Guide to Unix Using Linux, Fourth Edition 23 #!/usr/bin/perl # Program name: example9.pl %animals = (’Tigers’, 10, ’Lions’, 20, ’Bears’, 30); print ("The animal values are:\n"); print ("$animals{’Tigers’}\n"); print ("$animals{’Lions’}\n"); print ("$animals{’Bears’}\n"); ~]$./example9.pl The animal values are: Hashes (continued) Example: Output:

24 A Guide to Unix Using Linux, Fourth Edition 24 Perl Versus the Awk Program Unlike Perl, Awk does not require programmer to explicitly set up looping structures –Uses fewer lines of code to resolve pattern-matching extractions than Perl Similarities: –Perl and Awk use # to specify a comment line –Pattern-matching code is the same in both programs –Both are portable across many UNIX/Linux systems

25 A Guide to Unix Using Linux, Fourth Edition 25 #!/usr/bin/awk -f # Program name: awkcom.a # Purpose: Count the comment lines in a file. # Enter the file name on the command line. END { print "The file has ", line_count, " comment lines." } /^#/ && !/^#!/ { ++line_count } # This occurs for every line.

26 A Guide to Unix Using Linux, Fourth Edition 26 #!/usr/bin/perl # Program name: perlcom.pl # Purpose: Count the source file’s comment lines # ============================================== $filein = $ARGV[0]; while (<>) { if (/^#/ && !/^#!/) { ++$line_count } print ("File \"$filein\" has $line_count comment lines. \n"); <> is the diamond operator

27 A Guide to Unix Using Linux, Fourth Edition 27 How Perl Accesses Disk Files Perl uses filehandles to reference files Filehandle: name for an I/O connection between Perl program and OS –Used to open, read, write, and close the file –Convention: use all uppercase letters for filehandles Must issue an open before you can access file –Exception: when file name passed through ARGV[0] Three standard filehandles in Perl: –STDIN, STDOUT, and STDERR

28 A Guide to Unix Using Linux, Fourth Edition 28 #!/usr/bin/perl # Program name: perlread1.pl # Purpose: Display records in a file and count lines $filein = $ARGV[0]; while (<>) { print "$_"; ++$line_count; } print ("File \"$filein\" has $line_count lines. \n"); #!/usr/bin/perl # Program name: perlread2.pl # Purpose: Open disk file. Read and display the records # in the file. Count the number of records in # the file. open (FILEIN, "students") || warn "Could not open students file\n"; while ( ) { print "$_"; ++$line_count; } print ("File \"students\" has $line_count lines. \n"); close (FILEIN);

29 A Guide to Unix Using Linux, Fourth Edition 29 Using Perl to Sort Perl provides a powerful and flexible sort operator –Can sort string or numeric data In ascending or descending order –Allows advanced sorting Define your own sorting routine

30 A Guide to Unix Using Linux, Fourth Edition 30 Using Perl to Sort Alphanumeric Fields Perl can be used to sort information Example: #!/usr/bin/perl # Program name: perlsort1.pl # Purpose: Sort a list of names contained inside an array # Syntax: perlsort1.pl = ("Oranges", "Apples", "Tangerines", "Pears", "Bananas", = print print"\n";

31 A Guide to Unix Using Linux, Fourth Edition 31 Using Perl to Sort Alphanumeric Fields (continued) Another example: #!/usr/bin/perl # Program name: perlsort2.pl # Purpose: Sorts a text file alphabetically. File name is # entered on the command line. # Syntax: perlsort2.pl file name #======================================================== $x = 0; while (<>) { $somelist[$x] = $_; $x++; }

32 A Guide to Unix Using Linux, Fourth Edition 32 Using Perl to Sort Numeric Fields For numeric fields, you can define a subroutine with the comparison conditions sub numbers { if ($a < $b) { -1; } elsif ($a == $b) { 0; } else { +1; } } $sortednumbers = sort numbers 101, 87, 34, 12, 1, 76;

33 A Guide to Unix Using Linux, Fourth Edition 33 Using Perl to Sort Numeric Fields (continued) Perl has a special operator for numeric sorts: –Spaceship operator The inline sort block is even more compact sub numbers { $a $b; } $sortednumbers = sort numbers 101, 87, 34, 12, 1, = sort { $a $b;

34 A Guide to Unix Using Linux, Fourth Edition 34 #!/usr/bin/perl # Program name: perlsort3.pl # Purpose: Sorts numerically using a subroutine. File name # is entered on the command line. # Syntax: perlsort3.pl file name #======================================================== $x = 0; while (<>) { $somelist[$x] = $_; $x++; = sort sub numbers { if ($a < $b) { -1; } elsif ($a == $b) { 0; } else { +1; } }

35 A Guide to Unix Using Linux, Fourth Edition 35 Using Perl to Sort Numeric Fields (continued)

36 A Guide to Unix Using Linux, Fourth Edition 36 #!/usr/bin/perl # Program name: perlsort4.pl # Purpose: Sort numerically using the spaceship operator # ( ) # syntax: perlsort4.pl file name #======================================================== $x = 0; while (<>) { $somelist[$x] = $_; $x++; = sort sub numbers { $a $b; } Using Perl to Sort Numeric Fields (continued)

37 A Guide to Unix Using Linux, Fourth Edition 37 Setting Up a Web Page Create a Web page using HTML –HTML: Hypertext Markup Language Format for creating documents with embedded tags Tags give the document special properties and let you place hyperlinks in a document Publish a Web page on a Web server Experiment with and test HTML documents using your system’s loopback address – or localhost

38 A Guide to Unix Using Linux, Fourth Edition 38 Creating a Simple Web Page To create Web pages: –Use a visual HTML editor Examples: Adobe Dreamweaver, Microsoft Expression Web “What you see is what you get” –Use a text editor Examples: vi, Emacs Just type text and the desired embedded tags

39 A Guide to Unix Using Linux, Fourth Edition 39 My Simple Web Page Just a Simple Web Page This is a Web page with no frills!

40 A Guide to Unix Using Linux, Fourth Edition 40 Creating a Simple Web Page (continued) UNIX/Linux Programming Tools My UNIX/Linux Programming Tools Languages Perl Shell Scripts C and C++ Editors vi Emacs Other Tools awk sed

41 A Guide to Unix Using Linux, Fourth Edition 41 CGI Overview Perl is the most commonly used language for Common Gateway Interface (CGI) programming –CGI is a protocol governing how browsers and servers communicate Exchanging and processing a form containing information typically involves: –Using CGI for communication between the client’s Web browser and the Web server –A program that can be executed Often a Perl script or a program written in C Often stored in cgi-bin subdirectory on Web server

42 A Guide to Unix Using Linux, Fourth Edition 42 CGI Overview (continued) Programs in cgi-bin are set up to have executable permissions –Also typically have r permissions so client can view associated Web page To allow HTML document to accept input, precede input area with a description: Total Cost? Some links of interest: –www.scriptarchive.com –www.perl.com –www.perlaccess.com

43 A Guide to Unix Using Linux, Fourth Edition 43 Summary Perl is a scripting language –Data types: variables, constants, scalars, strings, arrays, and hashes Perl and Awk are both powerful processing languages that function in different ways Perl uses filehandles for the I/O connection between a file and Perl In Perl, use operator for numeric sorts HTML is used to format text in a Web page CGI is a protocol that governs how browsers and servers communicate

44 A Guide to Unix Using Linux, Fourth Edition 44 Command Summary


Download ppt "A Guide to Unix Using Linux Fourth Edition Chapter 9 Perl and CGI Programming."

Similar presentations


Ads by Google