1 / 51

Perl for the Web

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

edna
Download Presentation

Perl for the Web

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Perl for the Web Alexandra Cristea

  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.

  3. Perl: latest version • V 5.10 (Perl 6 in development) • Download from: http://www.perl.com/download.csp

  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.

  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/perl On Windows you can search for it with the Search function, but it’s best to remember where you installed it (probably in ‘Program Files’).

  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";

  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!";

  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

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

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

  11. Visit the code: hello.pl: #!/usr/bin/perl -w print "Content-type: text/html\n\n"; print "<H1>Hello World</H1>\n";

  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!!

  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 (\).

  14. escapecharacters.pl: #!/usr/bin/perl -w print "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.youremail@youremail.com$string and $email Check: http://prolearn.dcs.warwick.ac.uk/AHRO/escapecharacters.pl

  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);

  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 BROWSER print "@days"; print "<br />"; print "@months"; Check: http://prolearn.dcs.warwick.ac.uk/AHRO/definearrays.pl

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

  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.

  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 ARRAY print "@coins"; # PRINT EACH SCALAR ELEMENT print "<br />"; print $coins[0]; #Prints the first element print "<br />"; print $coins[1]; #Prints the 2nd element print "<br />"; print $coins[2]; #Prints the 3rd element Check: http://prolearn.dcs.warwick.ac.uk/AHRO/arrayindexing.pl

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

  21. definehashes.pl: #!/usr/bin/perl -w print "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

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

  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 IT while (($key, $value) = each(%coins)){ print $key.", ".$value."<br />"; } Check: http://prolearn.dcs.warwick.ac.uk/AHRO/legiblehash.pl

  24. legiblehash.pl: Nickel, 5 Dime, 10 Quarter, 25 Check: http://prolearn.dcs.warwick.ac.uk/AHRO/legiblehash.pl

  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.

  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

  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 STRINGS print $mystring."<br />"; print $newline."<br />"; print $capital."<br />"; print $ALLCAPS; Check: http://prolearn.dcs.warwick.ac.uk/AHRO/formattingcharacters.pl

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

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

  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.

  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 ARRAYS print @array."<br />"; print "@names"; Check: http://prolearn.dcs.warwick.ac.uk/AHRO/stringtoarray.pl

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

  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.

  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 ARRAYS print "@foods<br />"; print "@Foods"; Check: http://prolearn.dcs.warwick.ac.uk/AHRO/sortarrays.pl

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

  36. sortarrays2.pl: #!/usr/bin/perl -w print "content-type: text/html \n\n"; #HTTP HEADER @Foods = qw(Pizza Steak chicken burgers); print "@Foods";print "<br>"; # TRANSFORM TO LOWERCASE foreach $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

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

  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.

  39. substr() "Hello World! " $mystring = "Hello World! “; # replace all characters after the sixth character substr($mystring, 6) = "World!"; # replace characters between the 6th and the 11th substr($mystring, 6, 5) = "World"; 0 1 2 3 4 5 6 7 8 9 10 1112 Check: http://prolearn.dcs.warwick.ac.uk/AHRO/stringreplace.pl Check: http://prolearn.dcs.warwick.ac.uk/AHRO/stringreplace2.pl

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

  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 STRING print $mystring."<br />"; # RUN OUR FUNCTION AND CHANGE OUR STRING substr($mystring, 6, 5) = "Perl"; # PRINT THE NEW STRING print $mystring; Check: http://prolearn.dcs.warwick.ac.uk/AHRO/stringreplace2.pl

  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.

  43. Installing modules • make sure the following modules are installed: • DBI • DBD::mysql

  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

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

  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 database my $dbh = &dbconnect; # Report the result if (!$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

  47. Subroutine dbconnect: sub dbconnect { my %config = %{&dbconfig}; if (!%config) { return undef; } #set the port if port is not empty if ($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; };

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

  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();

  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();

More Related