2620520
TRANSCRIPT
-
7/29/2019 2620520
1/12
1
Programming on the Web(CSC309F)
Tutorial 7: Perl
TA:Wael Abouelsaadat
WebSite: http://www.cs.toronto.edu/~wael
Office-Hour: Friday 12:00-1:00 (SF2110)
Email: [email protected]
-
7/29/2019 2620520
2/12
2
Introduction to Perl History of Perl!
Initially developed byLarry Wall(English major student then!) in 1987.
Modules continuously added since version 2.0
Latest version is Perl 5.6.1
Ported to 83 platforms. Most popular scripting language for server-side web development.
Pros && Cons: Powerful in manipulating textual data.
A very rich set of pattern-matching operations (used extensively in text-searching, NLP systems,).
Rich set of functions (via Perl modules).
Allow you to get the job done very quickly (but not necessarily elegantly! ).
No GUI library.
Weird syntax (greatly reduces maintainability of Perl programs).
Perl is an interpreted language.
Unix influence (originally built as a replacement for shell scripts and awk).
helloworld.pl Source:
print ( Hello to Perl World! );print Hello to Perl World!; # yes, no brackets!
Run it:C:\> perl helloworld.plHello to Perl World!Hello to Perl World!
-
7/29/2019 2620520
3/12
3
Perl Data types Specifying Types and Containers:
Variables are not explicitly declared. Perl interpreter guesses the type from the way the variable is written.$var - names a variable that holds a scalar data type (integer, floating point or string).@var - names a variable that holds an array of scalars, or list.
%var - names a variable that holds an associative array of scalars.&var - names a subroutine.
E.g.#Defining a scalar$Name = "Jack";$Age = 10;
#Defining and handling an array@Colors = ("Red","Pink","Yellow");
$FirstColor = $Colors[0];print( $FirstColor ); # Outputs Red$Colors[0] = "White";
print( $Colors[0] ); # Outputs White$Colors[100] = Blue; # This is valid because Arrays in Perl are dynamic in sizeprint( $Colors[100] ); # Outputs Blue
print( $#Colors ); # Prints 100 which is the last index of the array. This is a unique variable# defined by the perl interpreter to give you access to current size of array
# Defining and handling a hash table
%Address = ("Apartment" => 101,"Street" => "Bloor",
"City" => "Toronto");$streetName = $Address{"Street"};print( $streetName ); # Outputs Bloor
$Address{"City"} = "Ottawa";print( $Address{"City"} ); # Outputs Ottawadelete $Address{"City"};
@tkeys = keys(%Address); # keys function returns an array of the keys in the hash table
Global vs. Local variables: $Name = John; # Visible in the whole programmy $Name = John; # Visible in the block it is declared in
-
7/29/2019 2620520
4/12
4
Perl Strings Strings:
Difference between using the single quote (') and the double quote (") to delimit strings:$Client = 'John Luu';
@Items = ( "Chocolate", "Biscuits", "Milk");$Total = 60;$Transaction = "$Client is buying @Items for \$ $Total";
print( $Transaction ); # Outputs John Luu is buying Chocolate Biscuits Milk for $ 60
Concatenating Strings:
$FirstName = John'; $LastName = Black;
$FullName = $First Name . $LastName; # FullName is now John Black
String operators:
# lt: less than , le: less or equal , eq: equal , ge: greater or equal , ne: not equal , eq: equal$Val1 = 1.1; $Val2 = 1.0;
$Val3 = bbb; $Val4 = aaa;if( ($Val1 gt $Val2) && ($Val3 lt $Val4 ) )
Pattern matching:
# =~: does match , !~: does not match$CatString = tomcatif ( $CatString =~ /cat/ ) . # Right-hand-side of these operators must always be a regular expression
-
7/29/2019 2620520
5/12
5
Perl Control , Loops and FunctionsControl statements:
If statement: Unless Statementif( $Size < 10.0 ) { unless( $Name eq John Black ){
print( "Length is too small!\n" ); print( You are not John Black );
} }elsif ( $Size > 100.0 ) {
print( "Length is too big!\n" );}else{
print( "Length is just right!\n" );
}
Looping:While Loops: For Loops:
while( $n
-
7/29/2019 2620520
6/12
6
Perl Functions contd Perl built-in functions:
Debugging Functions# caller( )# Unwinds the calling stack: ($package, $filename, $line,$SubName, $args,$$contentxt) = caller( $frame );
a( );sub a { b(); }sub b { c(); }sub c { print ( @{ [ caller(1) ] } ); } # Outputs main script.pl 2 main::b 1 0
# die( )
# Kills a process at a given point.open ( REPORT_FILE, ">report.txt" ) || die " Error opening report.txt $! \n " ;# The above translates to if( open( .) continue ) else { die . }
# warn( )# Does the same thing as die but does not exit.
Time Functions# ($secs , $min, $hr, $mday, $mnth, $yr, $wd, $yd, $ds ) = localtime( ); Gets local time# ($user, $system, $child_user, $child_system ) = times( ); Benchmark code
# sleep( $seconds );
Variable Functions# sort() Sorts an array in alphabetical order, or by a user-defined function.
@DestArray = ( Apples, Bananas, Carrots );@NewArray = sort( @DestArray ); #Be carefull with arrays of numbers
# split() Takes a scalar and separates it based on on the criteria user provides# @NewArray = split( $text, $ScalarName ); $text can be delimiter or regular expression@splitArray = spli( , , $scalarName );
# grep() Finds which element in an array satisfies a condition.#@NewArray = grep( EXPRESSION , @arrayToMatch );@Foods = ( turkey, lucky charms, oranges );@longFoods = grep( length($_) > 6 , @foods );
-
7/29/2019 2620520
7/12
7
Perl Functions contd# map() Makes a new array based on a transform from the old array.
# @NewArray = map( &function, @source_array );@NewArray = map( MyFunc( $_ ) , @SourceArray );
File Functions# $bytes = read( FILEHANDLE, $scalar, $length, $offset )
Open( FILEHANDLE, file );$bytes = read( FILEHANDLE, $input, 40, 20 ); # reads 40 characters from file into $input starting at 20
#printf [FILEHANDLE] $format_string, @arrayOfValues;use FileHandle;
my $Fhandle = new FileHandle( > my_file );$longvarb = This has 23 chars in it;printf $Fhandle %10.10s\n , $longvarb;
String Functions #chop( ) Deletes the last character in a scalar. If applied to Array, hash => does the same!
$line = Please chop the letter T;chop( $line );
# chomp( ) Deletes the new line character, at the end of the line, if exists.
# More funs: chr, crypt, hex, index, lc, length, oct, ord, pack, reverse, rindex, sprintf, substr, uc, ucfirst
Array Functions#pop, push, shift, splice, unshift
Hash Functions# delete, each, exists, keys, values
I/O Functions
# binmode, close, closedir, dbmclose, dbmopen, eof, fileno, flock, format, getc, print, printf, read, readdir,# rewinddir, seek, seekdir, select, syscall, sysread, sysseek, syswrite, tell, telldir, truncate, write
Files/Directories Functions# -X, chdir, chmod, chown, chroot, fcntl, glob, ioctl, link, lstat, mkdir, open, opendir, readlink, rename,
# rmdir, stat, symlink, umask, unlink, utime
-
7/29/2019 2620520
8/12
8
Perl Input and Output
Printing Output: Standard Output:
print( STDOUT "Hello World!\n" );
print( "Hello World! \n" ); Files:
open( OUT, ">test.dat" ); # Associates file handle with file
print( OUT This text will be written in the file " );
Reading input: Standard Output:
$NewLine = ; # Reads one complete line from standard input$ProgramArguments = ; # Refer to arguments on the command line.
# e.g. perl prog param1 param2 param3
Files:open( IN,
-
7/29/2019 2620520
9/12
9
Perl Program Structure Perl Files (.pl) vs Perl Modules (.pm)
Where is main()?
Require Statement Causes the Perl interpreter to execute the code in the require d file!
# foo.pl
perl codemore perl code.1;#-----------------------------------------------
# Poo.pl
require foo.pl;perl code # you can call functions in foo.pl
Defining a Perl package and the use statement Semi-Object Oriented Programming! Creates a namespace.# Student.pm#!/usr/sbin/perlpackage Student;sub new {
# Initialization code
}sub printDetails{
# perl code..}
#-------------------------------# foo.pl
use Student; # Like include in C++$new_student = new Student( );$new_student->printDetails( );
Another way to use use !
Use CGI qw(); # Uses a specific function in a module: qw use strict;
Forces Perl inter reter to be strict in usin t es. Will save ou a lot of time !
some code
func1
File.pl File.pm
func2
-
7/29/2019 2620520
10/12
10
Perl - CGI Handling Query String
# dispatcher.pluse strict;# Retrieving query string
$request_method = $ENV{REQUEST_METHOD};if( $request_method eq GET ){$query_string = $ENV{QUERY_STRING};
}elsif ( $request_method eq POST ){
read( STDIN , $query_string, $ENV{CONTENT_LENGTH} );
}else{
print(Invalid Request Method !);
exit( 1 );}# Extracting name-value pairs from query string (param1=value1¶m2=value2&..)
@name_value_paris = split( /&/, $query_string );foreach $name_value (@name_value_pairs){
($name, $value ) = split( /=/, $name_value );
#more Perl code..}
Generating HTMLprint Content-type: text/html\n\n;
print \n;print foo title \n;print ..
Print
-
7/29/2019 2620520
11/12
11
Perl - cgi.pm Using cgi.pm
use strict;use CGI qw(:standard);
print ( header( ) );print( start_html( Anna Web Page ) ); # Anna Web Pageprint( table( .) );print( a() ); # xyz
print( radio_group(..) );
print( end_html( ) ); #
-
7/29/2019 2620520
12/12
12
Assignment 3
What is it about?
What can you do right now? HTML (design and layout of the web pages)
JavaScript (validations)
What you need to learn?
Perl Cookies
CGI
HTML/
JavaScript/Cookies
Perl/
CGI/Cookies
Client(Web-Browser) Server(HTTP Server)
SMTP Server POP3 Server
SMTP POP3