Introduction to Perl Lecturer: Prof. Andrzej (AJ) Bieszczad Email: [email protected]Phone: 818-677-4954 “UNIX for Programmers and Users” Third Edition, Prentice-Hall, GRAHAM GLASS, KING ABLES Slides partially adapted from Kumoh National University of Technology (Korea) and NYU
48
Embed
Introduction to Perl Lecturer: Prof. Andrzej (AJ) Bieszczad Email: [email protected] Phone: 818-677-4954 “UNIX for Programmers and Users” Third Edition,
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
“UNIX for Programmers and Users”Third Edition, Prentice-Hall, GRAHAM GLASS, KING ABLES
Slides partially adapted from Kumoh National University of Technology (Korea) and NYU
Introduction to Perl
Prof. Andrzej (AJ) Bieszczad Email: [email protected] Phone: 818-677-4954 2
What is Perl?• Practical Extraction and Report Language
• Written in 1986 by Larry Wall
• Influenced from awk, sed, and C Shell
• Similar to ksh93, python, tcl, javascript
• Widely used for CGI scripting
• Freely available
Introduction to Perl
Prof. Andrzej (AJ) Bieszczad Email: [email protected] Phone: 818-677-4954 3
Running Perl in UNIX• Explicit invocation of a program
$ perl [options] program [arguments]
• Using the #! Directive in program
$ program [arguments]
• Command line expression
$ perl –e ’print ”hello\n”;’
• Debugging mode (opens a CLI debugger - similar to gdb, dbx, jdb, etc.)
$ perl -d program [args]
Introduction to Perl
Prof. Andrzej (AJ) Bieszczad Email: [email protected] Phone: 818-677-4954 4
Perl Example
#!/usr/bin/perl -w # THIS IS A COMMENT: -w issues warningsprint “What is your favorite color? “;$color = <STDIN>;chomp($color);if ($color eq ‘blue’){print “That is my favorite! \n”;
}elsif ($color =~ /black/){print “ I do like $color for my shoes\n”;
}else{print “$color is a nice choice \n”;
}
Introduction to Perl
Prof. Andrzej (AJ) Bieszczad Email: [email protected] Phone: 818-677-4954 5
Data Types• Basic data types: scalars, indexed arrays of scalars (lists), and associative arrays.
• Scalars are strings or numbers depending on context.
• Type of variable determined by special leading character:
$ scalar@ indexed array% associative array& function
• All data types have separate name spaces
Introduction to Perl
Prof. Andrzej (AJ) Bieszczad Email: [email protected] Phone: 818-677-4954 6
Data Types Examples• Scalars:
$str = “The world is round” ; # string variable$num = 134.99; # numeric variable
• Arrays
@students =(“Mike”, “Lisa”, “John”);print $students[0]; # print Mike$students[3]= “Julie”; # add a new element$size = @students; # size of the array (== 4)@students = (); # empty array
• Hashes
%emp =(“Julie”, “President”, “Mary”, “VP”);print $emp {“Julie”}; # print “President”$emp{“John”} = “controller”; # add an element
Introduction to Perl
Prof. Andrzej (AJ) Bieszczad Email: [email protected] Phone: 818-677-4954 7
Special Scalar VariablesImportant special variable:
$_ default pattern for operators
Plenty fo other variable:
$0 name of the currently running script
$$ the current PID
$? status of last pipe or system call
$. the current line number of last input
$] the version of perl being used
$< the real uid of the process
$> the effective uid of the process
Introduction to Perl
Prof. Andrzej (AJ) Bieszczad Email: [email protected] Phone: 818-677-4954 8
Special Array Variables@ARGV command line arguments
@INC search path for modules
@_ default for split and subroutine parameters
%ENV current environment
%SIG used to set signal handlers
sub trapped {print STDERR “Interrupted!\n”;exit 1;
}$SIG{’INT’} = ’trapped’;
Introduction to Perl
Prof. Andrzej (AJ) Bieszczad Email: [email protected] Phone: 818-677-4954 9
Operators• Perl uses all of C’s operators (except type casting and pointer operators), and adds:
• exponentiation: **, **=
• range operator: ..
@new = @old[30..50];print 1 .. 9;
• string concatenation: . , .=
$x = $y . &frob(@list) . $z;$x .= ”\n”;
• string repetitor operator: x
“fred” x 3 # is fredfredfred
Introduction to Perl
Prof. Andrzej (AJ) Bieszczad Email: [email protected] Phone: 818-677-4954 10
Numeric and String comparison operators
Comparison Numeric String
equal == eq
not equal != ne
less than < lt
greater than > gt
less than or equal to <= le
greater than or equal to >= ge
Introduction to Perl
Prof. Andrzej (AJ) Bieszczad Email: [email protected] Phone: 818-677-4954 11
# find power of 2 larger than a numberprint "Enter a number: ";$num = <STDIN>;$power = 1;$power *=2 until ($power >= $num);print "next power of 2 is $power\n";
Introduction to Perl
Prof. Andrzej (AJ) Bieszczad Email: [email protected] Phone: 818-677-4954 14
Another Flow Control Example# ask for a non-empty name{ print("What is your name? "); $name = <STDIN>; chop($name);
if (! length($name)) { print("Please try again\n"); redo; }
print("Thank you, " . uc($name) . "\n");}
do { print("What is your name? "); $name = <STDIN>; chomp($name);
if (! length($name)) { print("Please try again\n"); }
} until (length($name));
Introduction to Perl
Prof. Andrzej (AJ) Bieszczad Email: [email protected] Phone: 818-677-4954 15
• Mentioning a filehandle in angle brackets (<…>) reads next line:
• scalar context: returns line (with newline)
$line = <TEMP>;
• array context: returns all lines (with newlines)
@lines = <TEMP>;
Introduction to Perl
Prof. Andrzej (AJ) Bieszczad Email: [email protected] Phone: 818-677-4954 19
I/O continued
• When used in a while construct, input lines are automatically assigned to the $_ variable.
• Typical usage: iterate over file one line at a time, using $_
while ( <> ) {next if /^#/; # continue - skip comments == if line starts with #last if /STOP/; # break - stop if a line with “STOP” reads/left/right/g; # global substitute: left --> rightprint; # print $_
}
• <> means all files supplied on command line (or STDIN if none) put together
Introduction to Perl
Prof. Andrzej (AJ) Bieszczad Email: [email protected] Phone: 818-677-4954 20
Files• Opening a file
open(PWD, ”/etc/passwd”);open(TMP, ”>/tmp/foobar.$$”);open(LOG, ”>>logfile”);open(TOPIPE, ”| lpr”);open(FROMPIPE, ”ps –ef |”);open(PWD, ”/etc/passwd”) or die ”cannot open”;
• Printing:
print LOG ”This is a log entry\n”;printf LOG ”entry: %s\n”, $var
• awk influence
$, field separator (column delimiter)$/ record separator (line delimiter)
Introduction to Perl
Prof. Andrzej (AJ) Bieszczad Email: [email protected] Phone: 818-677-4954 21
I/O Example# Read an array from a file$buffer = "";
Prof. Andrzej (AJ) Bieszczad Email: [email protected] Phone: 818-677-4954 31
String functions• Several C string manipulation functions:
– crypt, index, rindex, length, substr, sprintf
• Adds others:– chop: removes the last character from a string (very useful for removing \n character)– chomp: removes last character only if \n– work with scalars or arrays
Prof. Andrzej (AJ) Bieszczad Email: [email protected] Phone: 818-677-4954 35
Packages (Modules)• A collection of functions
– Usually stored in a file called MyModule.pm
• Each has its own namespace– Access with: $MyModule::Variable– Default package is $main
• To use a package: use MyModule;
• To create a module:– Start off with: package MyModule;– Definitions of subroutines and variables– Export routines/variables to global namespace– Indicate success with line:
1; #last statement in file
• Many available packages:– e.g., CGI
Introduction to Perl
Prof. Andrzej (AJ) Bieszczad Email: [email protected] Phone: 818-677-4954 36
Perl as a CGI scripting language• CGI - Common Gateway Interface
– allows for embedding actions on Web pages
– Java Servlet - same idea, but needs a Java Application Server (J2EE)– Microsoft has .Net
Web Browser Web Browser
html
Web Browser Web Server
cgi CGI Engine
html
e.g., Perl program e.g., Perl interpreter
Simple file serving
Similarly, .txt, .jpg, .pdf, etc.
Introduction to Perl
Prof. Andrzej (AJ) Bieszczad Email: [email protected] Phone: 818-677-4954 37
cgi.pm• Perl module for CGI parsing (Perl 5 and newer)
– Also includes utility functions for generating HTML, debugging, etc.
Prof. Andrzej (AJ) Bieszczad Email: [email protected] Phone: 818-677-4954 38
CGI Script: Example
Introduction to Perl
Prof. Andrzej (AJ) Bieszczad Email: [email protected] Phone: 818-677-4954 39
Part 1: HTML Form<html><center><H1>Anonymous Comment Submission</H1></center>Please enter your comment below which willbe sent anonymously to me.<p><form action=cgi-bin/comment.cgi method=post><textarea name=comment rows=20 cols=80></textarea><input type=submit value="Submit Comment"></form></html>
Introduction to Perl
Prof. Andrzej (AJ) Bieszczad Email: [email protected] Phone: 818-677-4954 40
open(MAIL, "|$sendmail -oi -t") or die "Can't open pipe to $sendmail: $!\n";print MAIL "To: $recipient\n";print MAIL "Subject: Sample Web Form Submission\n\n";print MAIL "$mail_body";close(MAIL) or die "Can't close pipe to $sendmail: $!\n";
Introduction to Perl
Prof. Andrzej (AJ) Bieszczad Email: [email protected] Phone: 818-677-4954 41
Part 2: CGI Script (Perl)
print "Content-type: text/html\n\n";print <<"EOF"; # print everything literally until the text<HTML><HEAD><TITLE>Thank you</TITLE></HEAD><BODY><H1>You submitted the following comment:</H1><pre>EOF # end of the first printprint $comment . "\n";print <<"EOF";</pre><H1>Thank you</H1><P>Thank you for your form submission.</BODY></HTML>EOF
Introduction to Perl
Prof. Andrzej (AJ) Bieszczad Email: [email protected] Phone: 818-677-4954 42
CGI environmentLogin to HP servers and do the following:
$ mkdir public_html$ cd public_html$ vi page.html # enter the HTML file$ chmod 644 page.html$ mkdir cgi-bin$ cd cgi-bin$ vi script.cgi # enter the CGI script (Perl program)$ chmod 755 script.cgi
Then open a browser and go to http://www.csun.edu/~yourname/page.html
Introduction to Perl
Prof. Andrzej (AJ) Bieszczad Email: [email protected] Phone: 818-677-4954 43
Another Example#!/usr/bin/perl# Dump parameters and environment variables
use CGI;
$query = CGI::new;print &CGI::header;
print "<H1> Date </H1>\n";print "<pre>\n";print `date\n`;print "</pre>\n";
Prof. Andrzej (AJ) Bieszczad Email: [email protected] Phone: 818-677-4954 44
Another Example with Database Access<html><head><title>User Database Access Test - perl</title></head><body><h1>User Database Access Test - perl</h1><p><form action="http://www.some.com/userData.cgi" method=post>A simple example to find information about a user data.<br>Enter your user ID name<input type=text name=“ID”><br><input type=submit value="Search database"></form><p></body></html>
Introduction to Perl
Prof. Andrzej (AJ) Bieszczad Email: [email protected] Phone: 818-677-4954 45
Another Example with Database Access#!/usr/local/bin/perluse CGI;# DBI is a module with a database connectoruse DBI;
$query = new CGI;# a debugging option that sends error messages to the browser rather# than log fileuse CGI::Carp qw(fatalsToBrowser);# print page headerprint "Content-type: text/html\n\n";print "<html><head><title>Location query</title></head>";print "<body><h1>Location query</h1><p>";# connect to the database “userDatabase” with ID “demo” and password “”$dbConnector = DBI->connect("dbi:mysql:userDatabase","demo","")
or die("Couldn't connect");# import names from the query page into a namespace ‘MySpace’$query->import_names(’MySpace');# prepare a database query$sqlTable = $dbConnector->prepare("select * from placeDatabase where feature = ?")
or die("Couldn't prepare");
Introduction to Perl
Prof. Andrzej (AJ) Bieszczad Email: [email protected] Phone: 818-677-4954 46
Another Example with Database Access# execute the query replacing ‘?’ with $MySpace::ID$sqlTable->execute($MySpace::ID);# are there any rows in the table?if($sqlTable->rows == 0){ print "No information for " . $MySpace::ID;}else{ print "<table border=2>\n";# get the row and put it into an associative array (a hash) while( $rowHash = $sqlTable->fetchrow_hashref() ) { print "<tr>"; print "<td>" . $rowHash->{”name”}; print "<td>" . $rowHash->{”address"}; print "<td>" . $rowHash- >{”telephone"}; print "<td>" . $rowHash- >{”email"}; print "\n"; } print "</table>\n";}print "</body></html>\n";# disconnect from the database$dbConnector->disconnect;
Ch. 2. UNIX for Non-Programmers
Perl Challenge
Introduction to Perl
Prof. Andrzej (AJ) Bieszczad Email: [email protected] Phone: 818-677-4954 48
Homework/Project• Read the CGI/Perl tutorials (see my links) - start with the “beginners”
• Implement the following Web-based pizza ordering system:
• You should have forms for:– delivery address– some selection for pizza (ingredients, style, etc.)– credit card information and– email address for confirmation.
• You do not need to store the data.
• You do not need to verify and charge credit card.
• The data collected from the form should be sent to your email address.
• A confirmation with order details should be displayed on the new page.
• You’ve got 3 weeks! I need the link to try out your program and your HTML file and CGI script.