Perl for the Web

51
Perl for the Web Alexandra Cristea

description

Perl for the Web. Alexandra Cristea. PERL - Practical Extraction and Report Language. - PowerPoint PPT Presentation

Transcript of Perl for the Web

Page 1: Perl for the Web

Perl for the Web

Alexandra Cristea

Page 2: Perl for the Web

2

PERL - Practical Extraction and Report Language• Created in 1987 by Larry Wall, the UNIX

based language has evolved into a powerful tool for the internet. It was designed as a quick-fix patch program for UNIX based systems. The language is very simplistic, offering optimum flexibility, perfect for short, straightforward scripting.

Page 3: Perl for the Web

3

Perl: latest version

• V 5.10 (Perl 6 in development)

• Download from:http://www.perl.com/download.csp

Page 4: Perl for the Web

4

Perl Editing• A PERL script can be created inside of any normal

simple-text editor program. There are several programs available for every type of platform (google for ‘free Perl editor’). There are many programs designed for programmers available for download on the web.

• Regardless of the program you choose to use, a PERL file must be saved with a .pl (.PL) file extension in order to be recognized as a functioning PERL script. File names can contain numbers, symbols, and letters but must not contain a space. Use an underscore (_) in places of spaces.

Page 5: Perl for the Web

5

PERL - First line• The first line of every PERL script is a commented

line directed toward the PERL interpreter:#!/usr/bin/perl • The comment points to the installation path of PERL. To find it, on Unix you type:-bash-3.1$ which perl/usr/bin/perlOn Windows you can search for it with the Search

function, but it’s best to remember where you installed it (probably in ‘Program Files’).

Page 6: Perl for the Web

6

HTTP Headers

• We have to introduce some HTTP headers so that PERL understands we are working with a web browser.

print "content-type: text/html \n\n";

Page 7: Perl for the Web

7

Hello world! Script• Now that we have located the

interpreter and told PERL we are working with the web, we can print text to the browser with the print function.

helloworld.pl:#!/usr/bin/perl print "content-type: text/html \n\n"; print "Hello World!";

Page 8: Perl for the Web

8

PERL - Execute Your First Script

• To execute your script, you need to upload it to a server with Internet access.

• After the upload allow anonymous execution privileges (0755):On UNIX:

chmod a+x helloworld.pl

If you check the rights, your new program should look like:-bash-3.00$ ls -al

-rwx--x--x 1 prolearn dcsother 93 May 2 14:40 hello.pl

Page 9: Perl for the Web

9

What should you see?• http://prolearn.dcs.warwick.ac.uk/AHRO/helloworld.pl

Page 10: Perl for the Web

10

A nicer one …• http://prolearn.dcs.warwick.ac.uk/AHRO/hello.pl• What is the difference?

Page 11: Perl for the Web

11

Visit the code:

hello.pl:

#!/usr/bin/perl -w

print "Content-type: text/html\n\n";

print "<H1>Hello World</H1>\n";

Page 12: Perl for the Web

12

Case Sensitivity• File names, variables, and arrays are all

case sensitive. If you capitalize a variable name when you define it, you must capitalize it to call it.

$VAriaBLE $VAriable are not the same!!

Page 13: Perl for the Web

13

Escaping Characters

• In PERL we use the backslash (\) character to escape any type of character that might interfere with our code. For example there may become a time when you would like to print a dollar sign rather than use one to define a variable. To do this you must "escape" the character using a backslash (\).

Page 14: Perl for the Web

14

escapecharacters.pl:#!/usr/bin/perl -wprint "Content-type: text/html \n\n"; #HTTP HEADER #CREATE STRINGS WITH ESCAPING CHARACTERS $string = "David paid \$4.34 for Larry\'s shirt."; $email = "youremail\@youremail.com";

#PRINT THE STRINGS print "$string<br />"; print "$email<br />"; print '$string and $email';

Output of escapecharacters.pl:David paid $4.34 for Larry's shirt.

[email protected]$string and $email

Check: http://prolearn.dcs.warwick.ac.uk/AHRO/escapecharacters.pl

Page 15: Perl for the Web

15

Variables

#!/usr/bin/perl

print "Content-type: text/html \n\n"; #HTTP HEADER

$myname = "some_value";

@array = ("value00","value01","value02");

%hash = ("Quarter", 25, "Dime", 10, "Nickle", 5);

Page 16: Perl for the Web

16

definearrays.pl:#!/usr/bin/perl -w

print "Content-type: text/html \n\n"; #HTTP HEADER

#DEFINE SOME ARRAYS@days = ("Monday", "Tuesday", "Wednesday");@months = ("April", "May", "June");

#PRINT MY ARRAYS TO THE BROWSERprint "@days";print "<br />";print "@months";

Check: http://prolearn.dcs.warwick.ac.uk/AHRO/definearrays.pl

Page 17: Perl for the Web

17

definearrays.pl

Check: http://prolearn.dcs.warwick.ac.uk/AHRO/definearrays.pl

Page 18: Perl for the Web

18

Array Indexing

• Each element of the array can be indexed using a scalar version of the same array. When an array is defined, PERL automatically numbers each element in the array beginning with zero. This phenomenon is termed array indexing.

Page 19: Perl for the Web

19

arrayindexing.pl:#!/usr/bin/perl -w

print "content-type: text/html \n\n"; #HTTP HEADER

# DEFINE AN ARRAY@coins = ("Quarter","Dime","Nickel");

# PRINT THE WHOLE ARRAYprint "@coins";

# PRINT EACH SCALAR ELEMENTprint "<br />";print $coins[0]; #Prints the first elementprint "<br />";print $coins[1]; #Prints the 2nd elementprint "<br />";print $coins[2]; #Prints the 3rd element

Check: http://prolearn.dcs.warwick.ac.uk/AHRO/arrayindexing.pl

Page 20: Perl for the Web

20

arrayindexing.pl:

Check: http://prolearn.dcs.warwick.ac.uk/AHRO/arrayindexing.pl

Page 21: Perl for the Web

21

definehashes.pl:#!/usr/bin/perl -wprint "Content-type: text/html \n\n"; #HTTP HEADER

#DEFINE SOME HASHES %coins = ("Quarter", 25, "Dime", 10, "Nickle", 5); %ages = ("Jerry", 45, "Tom", 22, "Vickie", 38);

#PRINT MY HASHES TO THE BROWSER print %coins; print "<br />"; print %ages;

Check: http://prolearn.dcs.warwick.ac.uk/AHRO/definehashes.pl

Page 22: Perl for the Web

22

definehashes.pl:

Check: http://prolearn.dcs.warwick.ac.uk/AHRO/definehashes.pl

Page 23: Perl for the Web

23

legiblehash.pl:#!/usr/bin/perl

print "content-type: text/html \n\n";

# DEFINE A HASH%coins = ( "Quarter" , 25, "Dime" , 10, "Nickel", 5 ); # LOOP THROUGH ITwhile (($key, $value) = each(%coins)){ print $key.", ".$value."<br />";}

Check: http://prolearn.dcs.warwick.ac.uk/AHRO/legiblehash.pl

Page 24: Perl for the Web

24

legiblehash.pl:

Nickel, 5

Dime, 10

Quarter, 25

Check: http://prolearn.dcs.warwick.ac.uk/AHRO/legiblehash.pl

Page 25: Perl for the Web

25

Strings

• Strings are scalar as we mentioned previously. There is no limit to the size of the string, any amount of characters, symbols, or words can make up your strings.

Page 26: Perl for the Web

26

definestrings.pl:#!/usr/bin/perl -w

print "content-type: text/html \n\n"; #HTTP HEADER

# DEFINE SOME STRINGS$single = 'This string is single quoted';$double = "This string is double quoted";$userdefined = q^Carrot is now our quote^;

# PRINT THEM TO THE BROWSER print $single."<br>";print $double."<br>";print $userdefined."<br>";

Check: http://prolearn.dcs.warwick.ac.uk/AHRO/definestrings.pl

Page 27: Perl for the Web

27

formattingcharacters.pl#!/usr/bin/perl -w

print "Content-type: text/html \n\n"; #HTTP HEADER

# STRINGS TO BE FORMATTED$mystring = "welcome to Web Programming!"; #String to be formatted$newline = "welcome to \nWeb Programming!";$capital = "\uwelcome to Web Programming!";$ALLCAPS = "\Uwelcome to Web Programming!";

# PRINT THE NEWLY FORMATTED STRINGSprint $mystring."<br />";print $newline."<br />";print $capital."<br />";print $ALLCAPS;

Check: http://prolearn.dcs.warwick.ac.uk/AHRO/formattingcharacters.pl

Page 28: Perl for the Web

28

formattingcharacters.pl

Check: http://prolearn.dcs.warwick.ac.uk/AHRO/formattingcharacters.pl

Page 29: Perl for the Web

29

formattingcharacters.pl

Check: http://prolearn.dcs.warwick.ac.uk/AHRO/formattingcharacters.pl

Page 30: Perl for the Web

30

Transform Strings to Arrays

• With the split function, it is possible to transform a string into an array. To do this simply define an array and set it equal to a split function. The split function requires two arguments, first the character of which to split and also the string variable.

Page 31: Perl for the Web

31

stringtoarray.pl:#!/usr/bin/perl -w

print "content-type: text/html \n\n"; #HTTP HEADER

# DEFINED STRINGS$astring = "Rain-Drops-On-Roses-And-Whiskers-On-Kittens";$namelist = "Larry,David,Roger,Ken,Michael,Tom";

# STRINGS ARE NOW ARRAYS@array = split('-',$astring);@names = split(',',$namelist);

# PRINT THE NEW ARRAYSprint @array."<br />";print "@names";

Check: http://prolearn.dcs.warwick.ac.uk/AHRO/stringtoarray.pl

Page 32: Perl for the Web

32

stringtoarray.pl:

Check: http://prolearn.dcs.warwick.ac.uk/AHRO/stringtoarray.pl

Page 33: Perl for the Web

33

Sorting Arrays• The sort() function sorts each element of an

array according to ASCII Numeric standards. Please view ASCII-Table for a complete listing of every ASCII Numeric character.

• Because the sort() relies on ASCII Numeric values, problems can arise with sorting capital letters and lower case letters. Let's walk through an example of exactly what can happen.

Page 34: Perl for the Web

34

sortarrays.pl:#!/usr/bin/perl -w

print "content-type: text/html \n\n"; #HTTP HEADER

# TWO ARRAYS@foods = qw(pizza steak chicken burgers);@Foods = qw(Pizza Steak chicken burgers);

# SORT 'EM@foods = sort(@foods);@Foods = sort(@Foods);

# PRINT THE NEW ARRAYSprint "@foods<br />";print "@Foods";

Check: http://prolearn.dcs.warwick.ac.uk/AHRO/sortarrays.pl

Page 35: Perl for the Web

35

sortarrays.pl:

Check: http://prolearn.dcs.warwick.ac.uk/AHRO/sortarrays.pl

Page 36: Perl for the Web

36

sortarrays2.pl:#!/usr/bin/perl -wprint "content-type: text/html \n\n"; #HTTP HEADER

@Foods = qw(Pizza Steak chicken burgers);print "@Foods";print "<br>";

# TRANSFORM TO LOWERCASEforeach $food (@Foods) { push (@foods, "\L$food");}

# SORT @foods = sort(@foods);

# PRINT THE NEW ARRAY print "@foods";

Check: http://prolearn.dcs.warwick.ac.uk/AHRO/sortarrays2.pl

Page 37: Perl for the Web

37

sortarrays2.pl:

Check: http://prolearn.dcs.warwick.ac.uk/AHRO/sortarrays2.pl

Page 38: Perl for the Web

38

Substr() and String Indexing• The substr() function allows for the temporary

replacement of characters in a string. We can change the string "Hello World! " to "Hello PERL" quite easily. Each character of the string is automatically assigned a numeric value by PERL, which means that we can index any of the characters in our strings with this number. PERL counts each character of the string beginning with 0 for the first character and continuing until it reaches the end of a string.

• Two arguments must be sent with our substr() function, the string you wish to index and the index number. If two arguments are sent, PERL assumes that you are replacing every character from that index number to the end.

Page 39: Perl for the Web

39

substr()$mystring = "Hello World! “;

# replace all characters after the sixth charactersubstr($mystring, 6) = "World!";

# replace characters between the 6th and the 11thsubstr($mystring, 6, 5) = "World";

"Hello World! "0 1 2 3 4 5 6 7 8 9 10 11 12

Check: http://prolearn.dcs.warwick.ac.uk/AHRO/stringreplace.pl

Check: http://prolearn.dcs.warwick.ac.uk/AHRO/stringreplace2.pl

Page 40: Perl for the Web

40

substr()Check: http://prolearn.dcs.warwick.ac.uk/AHRO/stringreplace.pl

Check: http://prolearn.dcs.warwick.ac.uk/AHRO/stringreplace2.pl

Page 41: Perl for the Web

41

stringreplace2.pl#!/usr/bin/perl -w

print "Content-type: text/html \n\n"; #HTTP HEADER

# DEFINE A STRING TO REPLACE$mystring = "Hello World!";

# PRINT THE BEGINNING STRINGprint $mystring."<br />";

# RUN OUR FUNCTION AND CHANGE OUR STRINGsubstr($mystring, 6, 5) = "Perl";

# PRINT THE NEW STRINGprint $mystring;

Check: http://prolearn.dcs.warwick.ac.uk/AHRO/stringreplace2.pl

Page 42: Perl for the Web

42

PERL - DBI Module(s)• PERL is capable of running SQL and MySQL

queries including: inserts, selects, updates, deletes, etc through a module termed DBI. Often your web host will already have this module as well as DBD::mysql already installed. DBI stands for database interface. Any functions associated with DBI should work with all the available SQL platform including: SQL Server, Oracle, DB2, and MySQL.

Page 43: Perl for the Web

43

Installing modules

• make sure the following modules are installed:

• DBI

• DBD::mysql

Page 44: Perl for the Web

44

dbtestdemo.cgi:#!/usr/bin/perl -w

use strict;use CGI;use DBI;

my $query = CGI->new();print $query->header();print $query->start_html(-title => "Home", -bgcolor => "#0066CC", -text =>

"WHITE", -link => "WHITE", -vlink => "LIGHTGREY", -ALINK => "RED");

print $query->p("Test of using DBI and CGI modules");

print $query->end_html;

Check: http://prolearn.dcs.warwick.ac.uk/AHRO/dbtestdemo.cgi

Page 45: Perl for the Web

45

dbtestdemo.cgi:

Check: http://prolearn.dcs.warwick.ac.uk/AHRO/dbtestdemo.cgi

Page 46: Perl for the Web

46

dbtest.cgi:# dbitestdemo + following:require "dbconnect.pl";my %config = %{&dbconfig};

print $query->p("Connecting to the database with parameters"), $query->dl( map { $query->dt($_ . ':'), $query->dd($config{$_}) } keys %config );

# Connect to the databasemy $dbh = &dbconnect;

# Report the resultif (!$dbh){ print $query->em("failed:"), $query->blockquote($DBI::errstr);}else{ print $query->em("succeeded."); $dbh->disconnect;}

Check: http://prolearn.dcs.warwick.ac.uk/AHRO/dbtest.cgi

Page 47: Perl for the Web

47

Subroutine dbconnect:sub dbconnect{ my %config = %{&dbconfig};

if (!%config) { return undef; }

#set the port if port is not emptyif ($config{'port'} && $config{'port'}!='') {

$ENV{'MYSQL_TCP_PORT'} = $config{'port'};}

my $dsn = "DBI:$config{'dbtype'}:database=$config{'database'};hostname=$config{'host'}:$config{'port'}";

my $dbh; eval { $dbh = DBI->connect(

$dsn, $config{'dbusername'}, $config{'dbpassword'} ) }; return $dbh;};

Page 48: Perl for the Web

48

dbtest.cgi:

Check: http://prolearn.dcs.warwick.ac.uk/AHRO/dbtest.cgi

Page 49: Perl for the Web

49

DBI Query# CONFIG VARIABLES$platform = "mysql";$database = "store";$host = "localhost";$port = "3306";$tablename = "inventory";$user = "username";$pw = "password";

# DATA SOURCE NAME$dsn = "dbi:$platform:$database:$host:$port";

# PERL DBI CONNECT$connect = DBI->connect($dsn, $user, $pw);

# PREPARE THE QUERY$query = "INSERT INTO inventory (id, product, quantity) VALUES

(DEFAULT, 'tomatoes', '4')";$query_handle = $connect->prepare($query);

# EXECUTE THE QUERY$query_handle->execute();

Page 50: Perl for the Web

50

DBI Select Queries:

# PREPARE THE QUERY$query = "SELECT * FROM inventory

ORDER BY id";$query_handle = $connect-

>prepare($query);

# EXECUTE THE QUERY$query_handle->execute();

Page 51: Perl for the Web

51

MySQL Insert Query:# SELECT DB$connect->selectdb($database);

# DEFINE A MySQL QUERY$myquery = "INSERT INTO $tablename (id, product, quantity) VALUES (DEFAULT,'pineapples','15')";

# EXECUTE THE QUERY FUNCTION$execute = $connect->query($myquery);