perl programming

40
30 April 2001 2 What is PERL? Perl is an acronym for "Practical Extraction and Report Language", It is an interpreted language that is optimized for string manipulation, I/O, and system tasks. It incorporates syntax elements from the Bourne shell, csh, awk, sed, grep, and C. It is FREE!

Upload: nitin-sharma

Post on 18-May-2015

2.939 views

Category:

Education


4 download

DESCRIPTION

PERL programming

TRANSCRIPT

Page 1: Perl programming

30 April 2001 2

What is PERL?

Perl is an acronym for "Practical Extraction and Report Language",

It is an interpreted language that is optimized for string manipulation, I/O, and system tasks. It incorporates syntax elements from the Bourne shell, csh, awk, sed, grep, and C.

It is FREE!

Page 2: Perl programming

30 April 2001 3

Form of a Perl Program Perl is a “scripted” language

Commands are usually placed in a text file which is then interpreted by the Perl interpreteer

Perl program are free-form whitespace is ignored between

tokens semicolon(;) used as statement

separator

Page 3: Perl programming

30 April 2001 4

Hello World! A simple program

#!/usr/bin/perl

print “Hello world\n”;

run a Perl program$ perl programname

Page 4: Perl programming

30 April 2001 5

Variables in PERL Three types of variables

Scalar: Single valued variables Array: A list of scalars indexed by number Hash: A list of scalars indexed by strings

All variables are global unless otherwise declared.

Page 5: Perl programming

30 April 2001 6

Scalars All scalars start with the $ character Scalars are typeless...no

differentiation between string, integer,floating point, or character values

No declaration needed to use a scalar $a=12; $b=‘hello’; $c=‘11’ ;

$d=$c * 2; # $d is 24 $e=“hello”;

Page 6: Perl programming

30 April 2001 7

Variable Interpolation Within double-quoted string, Perl performs direct

substitution of a variable’s value within that string. In single-quoted strings, no substitution is

performed. $d=224; $a=141; Print $d,”\n”; # 224 followed by newline Print “$d\n”; # same thing $sir=“is Perl”; $str=“$sir $a”; # $str equals “is Perl 141” print “This $str.\n”; #This is Perl 141. Print ‘This $str.\n’ ; #This is $str. \n

Page 7: Perl programming

30 April 2001 8

Arrays

Arrays start with the @ character Dynamically allocated; no size limits No ‘out of bound’ errors Arrays require no pre-initialization Heterogeneous values $a =1; $b =2; $c =3; @a =(1,2,3); # 1 2 3

@b =(‘Hello, ‘Baba’, ‘Mama’); # Hello Baba Mama@c =(123, ‘xyz’, 24, ‘what’); # 123 xyz 24 what@d =($a, $b, $c); # 1 2 3@e =(@a, @b); # 1 2 3 Hello Baba mama

Note that arrays are “flat”, @e has six scalar elements, not two array elements

Page 8: Perl programming

30 April 2001 9

Scalar and Array Distinction

The Scalar $a and array @a refer to different data values

$a = 141; @a = (‘yes’, ‘no’, ‘maybe’); Print “$a”; #141 Print “@a”; # yes no maybe

Page 9: Perl programming

30 April 2001 10

Accessing Individual Elements of an Array

@a = (‘yes’, ‘no’, ‘maybe’); $b = $a[1]; # $b is “no” $c = $a[2]; # $C is “maybe” We use the “$” here (instead of the “@’) because

the elements of an array are scalars. If we use the ‘@’, we get back a list:

@c = @a[2]; # @c = (‘maybe’) @d = @a[0,2,0,2,1]; # @d= (‘yes’, ‘maybe’, ‘yes’, maybe, ‘no’) Print $a[3]; # nothing

Page 10: Perl programming

30 April 2001 11

Interpolation of Arrays

If an array is placed in a double-quoted string, the elements of the array are substituted (separated by spaces):

@what= (‘an’, ‘array’);

print “ This is @what.”

# “This is an array.”

Page 11: Perl programming

30 April 2001 12

Array Functions join (‘expr’,list)

Joins the elements of list into a single string with elements separated by expr

@c = (‘Union’, ‘City of’, ‘New Jersey’, 08); print join(‘:’, @c); # Union:City of:New Jersey:08

split (/expr/, string) Splits string delimited by expr into an array of

strings

$x = ‘Union:City:New Jersey:08’; @a = split(/:/, $x); #@a= (‘Union’, ‘City’, ‘New Jerey’ ’08’)

Page 12: Perl programming

30 April 2001 13

More Array Functions

push (array, expr) Adds expr to the end of array@a = (1,2,3); push (@a, ‘what’); # @a = (1, 2, 3, ‘what’)

pop(array) Removes the last element of array and returns it $b = pop(@a); # $b = ‘what’, @a=(1,2,3)

unshift (array, expr) Similar to push(), but adds expr to the beginning of

array

shift (array) Similar to pop(), but removes the first element of array

and returns it

Page 13: Perl programming

30 April 2001 14

Continue

sort (array) returns the elements of array in sorted order @a = (‘abc’, 12, ‘bob’); @b = sort(@a); # @b = (12, ‘abc’, ‘bob’); @a unchanged

reverse (array) returns the elements of array in reverse order

@a = (‘abc’, ’12’, ‘bob’); @b = reverse(@a); # @b = (‘bob’, 12, ‘abc’)

Page 14: Perl programming

30 April 2001 15

Hashes

A hash stores a list of scalars indexed by string instead of numbers

Hash variables start with % character Elements in a hash are unordered Also called “associative arrays”

Hash Initialization: %users = (‘Adel’ => ‘Right’,

‘Hong’ => ‘Rainbow’,

‘Ali’ => ‘Power’);

Page 15: Perl programming

30 April 2001 16

Hash Access %users = ( ‘Adel’ => ‘Right’,

‘Hong’ => ‘Rainbow’, ‘Ali’ => ‘Power’ );

$a = $users{‘Adel’); # $a contains ‘Right’ $b = $users{ ‘Hong’); # $b contain ‘Rainbow’ ($c, $d) = @users{‘Adel’,’Hong’}; # multiple elements can be assigned to

scalars # simultaneously

Page 16: Perl programming

30 April 2001 17

Hash Functions

Keys (hash) returns an unordered list of the keys in hash

%users = (‘Adel => ‘Right’,‘Hong’ => ‘Rainbow’, ‘Ali’ => ‘Power’);

# %user = (‘Adel’, ‘Right’, ‘Hong’, ‘Rainbow’, ‘Ali’, ‘Powel’);@k = keys(%users); # @k = ( ‘Hong’, ‘Ali’, Adel’)

values(hash) returns an unordered list of values in

hash @v = values(%users); # @v = (‘Rainbow, Power’, ‘Right’)

Page 17: Perl programming

30 April 2001 18

Foreach Looping If, for while C/C++/Java like for loop

Foreach loop ( new ) @words = (“Now”, “is”, “the”,

“time”);

foreach $w (@words) { print “$w”;}

# Nowisthetime

Page 18: Perl programming

30 April 2001 19

File I/O

Special Filehandles STDIN Compare C++ cin STDOUT cout STDERR cerr

Diamond Operator: <> Read input from keyboard $name = <STDIN>;

Reads lines from files given on the command line or STDIN if nongiven

Returns false (undef) on end-of-file

Page 19: Perl programming

30 April 2001 20

User Defined Subroutines

Hi ( ); # Hello! Welcome to! Hi (‘everybody’); #Hello everybody! Welcome to Hi (‘everybody’,’Kean University’) ; #Hello everybody! Welcome to Kean University

sub Hi { ($name, $city) = @_; $name = $_[0]; $city = $_[1]; print “Hello $name! Welcome to $city”;}

Page 20: Perl programming

30 April 2001 21

Wed application using PERL/CGI

A simple adder

Enter the first number Enter the second number

Add Reset

Page 21: Perl programming

30 April 2001 22

Html code<html><head><title>Adder</title></head><body><p align="center”>A simple adder</p><form method="POST" action= "http://www.askli.com/cgi-bin/add.cgi">

<p align="center">Enter the first number<input type="text" name="num1" > </p>

<p align="center">Enter the second number<input type="text" name="num2" ></p>

<p align="center"><input type="submit" value="Add" name="B1"></p>

</form></body></html>

Page 22: Perl programming

30 April 2001 23

Wed application using PERL/CGI Read input from HTML form post method

read(STDIN, $data, ENV{"CONTENT_LENGTH"});

@field = split(/&/, $data);

foreach $item (@field){

($name, $value) = split(/=/, $item);

$value{$name} = $value;

}

Page 23: Perl programming

30 April 2001 24

Continue Read input from HTML get method Use CGI qw(param)

$num1= param("num1");

$num2 = param(“num2"); Where num and sec are names of

input fields from HTML form

Page 24: Perl programming

30 April 2001 25

Create HTML document#!/usr/bin/perluse CGI qw(param);read(STDIN, $data, ENV{"CONTENT_LENGTH"});@field = split(/&/, $data);foreach $item (@field){ ($name, $value) = split(/=/, $item); $value{$name} = $value;} print "Content-type: text/html\n\n";print “<html><head>”;Print <<start;<title> Grade Summary/title></head><body >Summation =StartPrint “$sum”; Print “</body></html>”;

Page 25: Perl programming

30 April 2001 26

Hands-on1. Open add.html 2. If you wish, you can add more in

your HTML3. Set the method attribute in form

as either get or post4. Set the

action=“http://www.askli.com/cgi-bin/add_yourname.cgi”

Page 26: Perl programming

30 April 2001 27

Continue: Edit the perl/cgi program

1. Copy add.cgi to add_yourname.cgi

2. open add_yourname.cgi from notepad

3. After 3rd line insert, if you use get method in html$num1= param("num1");$num2 = param(“num2");

4. Insert following if you use post method in html

read(STDIN, $data, ENV{"CONTENT_LENGTH"});

@field = split(/&/, $data);

foreach $item (@field){

($name, $value) = split(/=/, $item);

$value{$name} = $value;}

$num1 = $value{“num1”};

$num2 = $value{“num2”};

Page 27: Perl programming

30 April 2001 28

Continue$sum = $num1+$num2;print "Content-type: text/html\n\n";print “<html><head>”;Print <<start;<title> Grade Summary/title></head><body >Summation =StartPrint “$sum”;Print “</body></html>”;

Page 28: Perl programming

30 April 2001 29

continue Save the add_yourname.cgi Use the ftp to upload the

add_yourname.cgi to server Test: open add.htm click on add

Page 29: Perl programming

30 April 2001 30

PERL AS A DATABASE TOOL USING DBI

What is DBI( DataBase Inteface)? DBI is an interface specification for

accessing databases from Perl programsAllows Perl programs to access databases

in Oracle, mySQL, Informix, SQL Server, etc.

DBI is a database-independent set of routines for manipulating databases

DBD (DataBase Driver)modules interface between DBI and the underlying database management system (these are specified to a particular database you intend to use)

Page 30: Perl programming

30 April 2001 31

Continue How do I find out which drivers (DBDs)

are installed? #!/usr/bin/perl Use DBI; @drivers = DBI -> available_drivers (); Foreach $driver (@drivers) { print “ $driver\n”;}

For example, the above code may produce:

Proxy Mysql Oracle

Page 31: Perl programming

30 April 2001 32

Connecting to a database #!/usr/bin/perl use DBI; $datasource = “dbi:mysql:database_name”;

$Username = “guest”; $password = “changeme”; $dbh = DBI - > connect ($databsource, $username, $password);

# Perform some operations on the database

$dbh ->disconnect();

Page 32: Perl programming

30 April 2001 33

Executing SQL Statements Use the do () routine:

$dbh -> do (“ CREAT TABLE people ( lname CHAR(10), fname CHAR(10), city CHAR(20), country CHAR(10))”);

$dbh -> do(“ INSERT INTO people VALUES (‘ALI’, ‘Setoodehnia’, ‘Sirjan’,’IRAN’)”);

$dbh -> do(INSERT INTO people VALUES (‘HONG’, ‘LI’,’Zhengzhou’,’CHINA’)”);

$dbh -> do(INSERT INTO people VALUES (‘Adel’, ‘Setoodehnia’,’Norman’,’OK’)”);

Page 33: Perl programming

30 April 2001 34

Querying a database prepare/execute

$sql = “SELECT * FROM people”;

$sth = $dbh ->prepare ($sql”);

$sth ->execute (); retrieving data

@row = $sth -> fetchrow_array(); # return one row as array from the query

$href = $sth -> fetchrow_hashref(); %row = %{$href};

Page 34: Perl programming

30 April 2001 35

Querying a database #!/user/bin/perl Use DBI; $dbh = DBI -> connect (‘dbi: mysql:test’, ‘user’, ‘pass’); $sth = $dbh -> prepare (“SELECT * FROM people”); $sth -> execute (); while (@row = $sth -> fetchrow_array ( ))

{ ($lname, $fname, $city, $country) = @row; print “$fname $lname is from $city ,

$country\n”;} $dbh ->disconnect (); Ali Setoodehnia is from Sirjan, Iran Hong Li is from Zhengzhou, CHINA Adel Setoodehnia is from Norman,OK

Page 35: Perl programming

30 April 2001 36

Continue #!/user/bin/perl use DBI; $dbh = DBI -> connect (‘dbi:mysql:test’, ‘user’,

‘pass’); $sth = $dbh -> prepare(“ SELECT fname, lname, city

WHERE Country = ‘CHINA’ ORDER BY fname”); $sth -> execute(); while (@row = $sth -> fetchrow_array ( )) { ($lname, $fname, $city) = @row; print “$fname $lname is from $city CHINA\n”;}

Hong Li is from Zhengzhou, CHINAJin Li is from Zhengzhou, CHINA

Page 36: Perl programming

30 April 2001 37

Example Application

http://www.kean.edu/~ASEE http://www.askli.com

Page 37: Perl programming

30 April 2001 38

Answer using do() #!/usr/bin/perl $dbh = DBI -> connect (‘dbi:mysql:test’, ‘user’,

‘pass’); open (INFILE, “<tfile”) || die :”can’t open

tfile”; while ($line = <INFILE>) {

Chomp $line; ($lname, $fname, $city, $country)= split(/:/,

$line); $dbh->do(“INSERT INTO people VALUES (‘$lname’,

‘$fname’,’$city’, ‘$country’)”); }

$dbh -> disconnect; This method is inefficient because that the SQL

must be read and parsed for each row It is also unsafe due to quoting issues

Page 38: Perl programming

30 April 2001 39

Better answer using placeholders What are placeholders? Executing the same SQL statement with different

set of data #!/usr/bin/perl $dbh = DBI -> connect(‘dbi:mysql:test’, ‘user’,‘pass’); $sth = $dbh -> prepare(“INSERT INTO people VALUES (?,?,?,?)”); Open (INFILE, “<tfile”) || die “Can’t open tfile”; while ($line = >INFILE>) { chomp $line;

($lname, $fname, $city, $country) = split(/:/,$line); $sth ->execute ($lname, $fname, $city, $country); }

$dbh -> disconnect;

Page 39: Perl programming

30 April 2001 40

Error Handling in DBI How do you know when thing goes wrong?

DBI routines return a false value when there is an error

The special variable $DBI: : errstr is set to an appropriate error message

$dbh -> connect (‘dbi:mysql:x’, ’user’, ‘pass’) || die”Unable to connect - $DBI: :errstr\n”;

$sth = $dbh ->prepare(“SELECT * FROM people”) || die “You have an error in your SQL - $DBI: :

errstr\n”; $sth -> execute() ||

die “Error executing the SQL - $DBI: :errstr\n”;

Page 40: Perl programming

30 April 2001 41

RESOURCES DBI-http://rpmfind.net/linux/rpm2html/search.php?

query=perl-DBI

DBD-http://www.perl.com/CPAN-local/modules/by-module/DBD/