200 likes | 295 Vues
Learn practical uses of Perl, an interpreted language with syntax similar to C. Explore functions, variables, arrays, file handling, and hash structures. Master Perl for CGI applications.
E N D
CSC3530Software Technology Tutorial Two PERL Basics
PERL Basics • Practical Extraction and Report Language • It is interpreted (no need to compile) • Java is something in between, both compile and interpreted • Syntax similar to C language • Loosely typed language • No type like int, double, char, BOOL • Why Perl for CGI? • For the same CGI program, Perl is much shorter than C
Simple Example #!usr/bin/perl –w # this is a simple hello program print ‘Hi, I am computer. What’s your name?’; $name=<STDIN>; chomp $name; print “Hi $name, nice to meet you\n”; exit(0); • #!usr/bin/perl –w • Location of perl interpreter, use whereis perl to get it • -w switch to enable warning • Place your comment after # • All statements end with ;
Cont’d • print – function to print strings to standard output (monitor) • $name – all scalar variables in perl start with $ • <STDIN> - read input from standard input (keyboard) • <FILE> - file handle to read input from file, will be described later • chomp – function to remove new line character (\n) • exit – end the program
Properties of Perl • Function call may or may not need () • No main function • Do not need to declare variable at first • Strings are enclosed by “” or ‘’ • “” will try to evaluate variable inside e.g. “Hi, $name” while ‘Hi, $name’ will not • This is call variable interpolation • +,-,*,/,% similar to C • ** means to the power of, e.g. $eight=2**3; # $eight will be 8
Boolean in Perl • Things in Perl that considered as false • Number zero $false=0; • Empty string $false=“”; • String zero $false=“0”; • Undefined $false; • Comparison • ==, >, <, >=, <=, !=, eq, gt, lt, ge, le, ne • Logical operator • &&, ||, !, and, or, not • Short circuit • open (FH,”file.txt”) || die “cannot open file” • If file open is successful, the later statement will not be executed, otherwise, it will be executed and program terminated
Array in Perl • Array in Perl start with @ e.g. @terms=(‘RSA’,’DES’,’OLAP’,’OSI’,’Middleware’); for ($i=0;$i<=$#terms;$i++) { print “$terms[$i] ”; } Output: > RSA DES OLAP OSI Middleware • $terms[$i] – the (i+1)th element, array in perl counts from 0 • $#terms returns the index of the last element in the array • Can be replace by @terms=qw(RSA DES OLAP OSI Middleware);qw is a function : quote word
Cont’d • Another way to do this @terms=qw(RSA DES OLAP OSI Middleware); foreach $item(@terms) { print “$item “; } # more straight forward foreach (@terms) { print “$_ “; } • Both are the same, $_ is a special variable, many functions use it as default parameter,we will talk about this later, perhaps
Flow of Control • Most are similar to C • if (condition) {statement} elsif (condition) {statement} else {statement} • while (continuing condition) {statement} • for (A;B;C) {statement} • A – initialization • B – continuing condition • C – statement to be executed every iteration • Breaking the loop • last – similar to break in C • next – similar to continue in C
Cont’d • Two examples while ($i<15) { last if ($i==7); $i++; } # $i in here equal 7; for ($i=0; $i<100; $i++) { next if (not $i % 2); print “An odd number =$i\n”; #only odd number goes here }
FILE I/O • Simple file copy program #!/usr/bin/perl –w open(SOURCE,‘c:\\sourcefile.txt’) || die ‘Cannot open source’; open(DEST,’>c:\\destfile.txt’) || die ‘Cannot open dest’; @contents=<SOURCE>; #read all the lines into array print DEST @contents; #print all the lines close(SOURCE); close(DEST); #can be shorter, replace 2 lines by: print DEST <SOURCE>; • > sign is to indicate we want to write something to this file • @contents=<SOURCE> is a little bit lazy, you may use a for loop instead • print DEST @contents is to print all lines to the DEST file handle, if we omit it, the default is STDIN (monitor)
Hash structure • Hash is like a table lookup • e.g. telephone directory • Hash structure begins with % %name=(‘3530’, ‘software technology’, ‘5280’, ‘image processing’, ‘5110’, ‘advance software eng.’); print “3530: $name{‘3530’}\n”; print “5280: $name{‘5280’}\n”; Output: 3530: software technology 5280: image processing • Course codes are key, while course names are values • Key value pair can be added dynamically $name(‘5180’)=‘data mining’; #a key value pair is added {‘3530’}
More about hash print “We have these keys in our hash table\n”; foreach $key (keys %name) { print “$key\n”; } print “We have these values in our hash table\n”; foreach $value (values %name) [ print “$value\n”; } If (exists $name{‘5120’}) { print “we have key 5120 in the hash table\n”; } else { ` print “we do not have key 5120 in the hash table\n”; } #correct ways to check whether the key,value pair exist
Split, Join • Given a query string, How to retrieve the value input by user? ID=LJ4000&Category=printer&Price=700 $string=$ENV{‘QUERY_STRING’}; #get the query string @pair=split(/&/,$string); for each(@pair) { ($name,$value)=split(/=/,$_); print “$name = $value\n”; } Output: ID = LJ4000 Category = printer Price = 700 • Join will be discussed later in this tutorial
Functions (sub-routine) • Perl allow recursion • Functions in perl are defined like: sub function_name { statements; } • Argument stored in @_ (a special array variable) • You do not need to specify the number of argument • Handle this carefully, you should know what you are doing • Argument are all passed by reference • Better use my to declare local variable
More about function sub mean { my (@data)=@_; # my – indicate a local variable my $sum; foreach (@data) { $sum+=$_; } return ($sum/@data); } sub compare { my ($a, $b)=@_; # a way to retrieve parameters if ($a>$b) { return (1); } elseif ($a<$b) { return (-1); } else { return (0); } }
Basic CGI • We will introduce a perl CGI example that enable you to get values from a form and manipulate. • www2.cse.cuhk.edu.hk/~csc3530/student_data.htm,use proxy.cse.cuhk.edu.hk and port 8000use view source to check HTML code Name: id Name: name Name: major Name: csc1500,csc2510,csc2520 Name: level
Simple example #!/usr/local/bin/perl5 -w use CGI qw(:standard); # use the CGI module use strict; # variable declaration more strict sub no_input { print header(); # Content-type:….. print start_html('Error'); print qq(<p>No input parameter</p>); print end_html(); } if (!param) { # check input parameter no_input; } else { my $id=param('id'); my $name=param('name');
Cont’d my $major=param('major'); my $level=param('level'); my $csc1500=param('csc1500'); my $csc2510=param('csc2510'); my $csc2520=param('csc2520'); # get values open (STAT,">>/uac/cprj/csc3530/www/cgi-bin/stat.txt"); my $data=join (',',($id, $name, $major, $level, $csc1500, $csc2510, $csc2520)); print STAT "$data\n"; close (STAT); print header(); print start_html('Statistic'); print qq(<p>Thanks for your support!</p>); print end_html(); }
Next Week • Issues on making CGI to work • Servers in CSE • In depth discussion of CGI programming • Example similar to project • Supplier database • SQL – (may be) • insert, update, select