440 likes | 580 Views
A Guide to Unix Using Linux Fourth Edition. Chapter 9 Perl and CGI Programming. 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.
E N D
A Guide to Unix Using Linux Fourth Edition Chapter 9 Perl and CGI Programming
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 A Guide to Unix Using Linux, Fourth Edition
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 A Guide to Unix Using Linux, Fourth Edition
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 A Guide to Unix Using Linux, Fourth Edition
Introduction to Perl (continued) #!/usr/bin/perl # Program name: example1.pl print("This is a simple\n"); print("Perl program.\n"); A Guide to Unix Using Linux, Fourth Edition
Introduction to Perl (continued) • The following script uses a variable: • Output: #!/usr/bin/perl # Program name: example2.pl $name = "Charlie"; print ("Greetings $name\n"); [ellen@localhost ~]$ ./example2.pl Greetings Charlie A Guide to Unix Using Linux, Fourth Edition
Introduction to Perl (continued) #!/usr/bin/perl # Program name: example3.pl print ("Enter a number: "); $number = <STDIN>; print ("You entered $number\n"); A Guide to Unix Using Linux, Fourth Edition
Introduction to Perl (continued) #!/usr/bin/perl # Program name: example4.pl print ("Enter a number: "); $number = <STDIN>; if ($number == 10) { print ("That is the number I was thinking of.\n"); } else { print ("You entered $number\n"); } A Guide to Unix Using Linux, Fourth Edition
Introduction to Perl (continued) A Guide to Unix Using Linux, Fourth Edition
Introduction to Perl (continued) A Guide to Unix Using Linux, Fourth Edition
Introduction to Perl (continued) • Perl offers the if-else statement: • Output: #!/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"); } [ellen@localhost ~]$ ./example5.pl Hello. My name is Ellen A Guide to Unix Using Linux, Fourth Edition
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"); [ellen@localhost ~]$ ./example6.pl The average is 24 A Guide to Unix Using Linux, Fourth Edition
Identifying Data Types • In Perl, data can be represented in a variety of ways • Variables and constants • Scalars • Numbers • Strings • Arrays • Hashes A Guide to Unix Using Linux, Fourth Edition
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 = 127.89 A Guide to Unix Using Linux, Fourth Edition
Scalars • Scalar: simple variable that holds a number or string • Name begins with a $ • Examples: • $x = 12; • $name = "Jill"; • $pay = 12456.89; A Guide to Unix Using Linux, Fourth Edition
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 A Guide to Unix Using Linux, Fourth Edition
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 A Guide to Unix Using Linux, Fourth Edition
Strings (continued) A Guide to Unix Using Linux, Fourth Edition
#!/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"); A Guide to Unix Using Linux, Fourth Edition
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 A Guide to Unix Using Linux, Fourth Edition
#!/usr/bin/perl # Program name: example8.pl @pets = ("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"); A Guide to Unix Using Linux, Fourth Edition
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’} A Guide to Unix Using Linux, Fourth Edition
Hashes (continued) • Example: • Output: #!/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"); [ellen@localhost ~]$ ./example9.pl The animal values are: 10 20 30 A Guide to Unix Using Linux, Fourth Edition
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 A Guide to Unix Using Linux, Fourth Edition
#!/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. A Guide to Unix Using Linux, Fourth Edition
#!/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 A Guide to Unix Using Linux, Fourth Edition
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 A Guide to Unix Using Linux, Fourth Edition
#!/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 (<FILEIN>) { print "$_"; ++$line_count; } print ("File \"students\" has $line_count lines. \n"); close (FILEIN); A Guide to Unix Using Linux, Fourth Edition
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 A Guide to Unix Using Linux, Fourth Edition
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 <Enter> #======================================================== @somelist = ("Oranges", "Apples", "Tangerines", "Pears", "Bananas", "Pineapples"); @sortedlist = sort @somelist; print "@sortedlist"; print"\n"; A Guide to Unix Using Linux, Fourth Edition
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 <Enter> #======================================================== $x = 0; while (<>) { $somelist[$x] = $_; $x++; } A Guide to Unix Using Linux, Fourth Edition
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; A Guide to Unix Using Linux, Fourth Edition
Using Perl to Sort Numeric Fields (continued) • Perl has a special operator for numeric sorts: <=> • Spaceship operator • The inline sort blockis even more compact sub numbers { $a <=> $b; } $sortednumbers = sort numbers 101, 87, 34, 12, 1, 76; @sortednumbers = sort { $a <=> $b; } @numberlist; A Guide to Unix Using Linux, Fourth Edition
#!/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 <Enter> #======================================================== $x = 0; while (<>) { $somelist[$x] = $_; $x++; } @sortedlist = sort numbers @somelist; print @sortedlist; sub numbers { if ($a < $b) { -1; } elsif ($a == $b) { 0; } else { +1; } } A Guide to Unix Using Linux, Fourth Edition
Using Perl to Sort Numeric Fields (continued) A Guide to Unix Using Linux, Fourth Edition
Using Perl to Sort Numeric Fields (continued) #!/usr/bin/perl # Program name: perlsort4.pl # Purpose: Sort numerically using the spaceship operator # (<=>) # syntax: perlsort4.pl file name <Enter> #======================================================== $x = 0; while (<>) { $somelist[$x] = $_; $x++; } @sortedlist = sort numbers @somelist; print @sortedlist; sub numbers { $a <=> $b; } A Guide to Unix Using Linux, Fourth Edition
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 • 127.0.0.1 or localhost A Guide to Unix Using Linux, Fourth Edition
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 A Guide to Unix Using Linux, Fourth Edition
<HTML> <HEAD><TITLE>My Simple Web Page</TITLE></HEAD> <BODY> <H1>Just a Simple Web Page</H1> This is a Web page with no frills! </BODY> </HTML> A Guide to Unix Using Linux, Fourth Edition
Creating a Simple Web Page (continued) <HTML> <HEAD><TITLE>UNIX/Linux Programming Tools</TITLE></HEAD> <BODY> <H1><CENTER>My UNIX/Linux Programming Tools</CENTER></H1> <H2>Languages</H2> <P>Perl</P> <P>Shell Scripts</P> <P>C and C++</P> <H2>Editors</H2> <P>vi</P> <P>Emacs</P> <H2>Other Tools</H2> <P>awk</P> <P>sed</P> </BODY> </HTML> A Guide to Unix Using Linux, Fourth Edition
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 A Guide to Unix Using Linux, Fourth Edition
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? <INPUT TYPE=text NAME=cost SIZE=10> • Some links of interest: • www.scriptarchive.com • www.perl.com • www.perlaccess.com A Guide to Unix Using Linux, Fourth Edition
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 A Guide to Unix Using Linux, Fourth Edition
Command Summary A Guide to Unix Using Linux, Fourth Edition