CGI With Object Oriented Perl

24
Basic Introduction To Perl Programming

Transcript of CGI With Object Oriented Perl

Page 1: CGI With Object Oriented Perl

Basic Introduction To Perl Programming

Page 2: CGI With Object Oriented Perl

Perl is a highly capable, feature-rich programming language. Perl can be used both in Procedure Oriented & Object Oriented mode. Perl as a programming is preferred when application extensively requires text

processing (basically used in Network Programming e.g. Socket class programming)

CGI” stands for “Common Gateway Interface. CGI is a program intended to be run on the web.

Page 3: CGI With Object Oriented Perl

#!/usr/bin/perl The above line specifies the code following it is a perl program and should be save

with a .pl extension

Scalar Variables Contains a single piece of data i.e. one element--a string, a number, or a reference. Strings may contain any symbol, letter, or number. Numbers may contain exponents, integers, or decimal values

Example: #!/usr/bin/perl # DEFINE SOME SCALAR VARIABLES $number = 5; print $number;

Page 4: CGI With Object Oriented Perl

Array Variables( List Variables) Arrays contain a list of scalar data (single elements). A list can hold an unlimited number of elements. In Perl, arrays are defined with the at (@) symbol

Example: #!/usr/bin/perl #DEFINE SOME ARRAYS @days = ("Monday", "Tuesday", "Wednesday"); print @days;

print “@days”; [Displays the o/p nicely]

Hash Hashes are complex lists with both a key and a value part for each element of the list. We define a hash using the percent symbol (%).

Page 5: CGI With Object Oriented Perl

Example #!/usr/bin/perl

#DEFINE SOME ARRAYS %coins = ("Quarter", 25, "Dime", 10, "Nickle", 5); print %coins;

• File names, variables, and arrays are all case sensitive. If you capitalize variable name when you define it, you must capitalize it to call it.

Page 6: CGI With Object Oriented Perl

To define a string we use single or double quotations, you may also define them with the q subfunction. Example #!/usr/bin/perl

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 $single."<br />"; print $double."<br />"; print $userdefined."<br />";

Page 7: CGI With Object Oriented Perl

String Manipulation Character Description

\L Transform all letters to lowercase

\lTransform the next letter to lowercase

\U Transform all letters to uppercase

\uTransform the next letter to uppercase

\n Begin on a new line

\r Applies a carriage return

\t Applies a tab to the string

\f Applies a form feed to the string

\b Backspace

Page 8: CGI With Object Oriented Perl

Character Description

\a Bell

\e Escapes the next character

\0nn Creates Octal formatted numbers

\xnnCreates Hexideciamal formatted numbers

\cXControl characters, x may be any character

\Q Do not match the pattern

\E Ends \U, \L, or \Q functions

Page 9: CGI With Object Oriented Perl

Example #!/usr/bin/perl

print "content-type: text/html \n\n"; #HTTP HEADER# STRINGS TO BE FORMATTED$mystring = "welcome to TCS!"; $newline = "welcome to \nTCS!";$capital = "\uwelcome to TCS!";$ALLCAPS = "\Uwelcome to TCS!";# PRINT THE NEWLY FORMATTED STRINGSprint $mystring."<br />";print $newline."<;br />";print $capital."<br />";print $ALLCAPS";

Page 10: CGI With Object Oriented Perl

String Method Substring() : Used to grab a sub string out of a string as well as replace a substring with another. Example #!/usr/bin/perl

print "content-type: text/html \n\n"; # DEFINE A STRING TO REPLACE $mystring = "Hello, I am Bunty Ray!"; # PRINT THE ORIGINAL STRING print "Original String: $mystring<br />"; # STORE A SUB STRING OF $mystring, OFFSET OF 7 $substringoffset = substr($mystring, 7); print "Offset of 7: $substringoffset<br />";

O/p: Hello, I am Bunty Ray

I am Bunty Ray

Page 11: CGI With Object Oriented Perl

Operator Use

+ Addition

- Subtraction

* Multiplication

** Exponents

% Modulus

/ Division

Operator Use Syntax

+ = Addition ($x += 10)

- = Subtraction ($x -= 10)

* = Multiplication ($x **= 10)

** = Exponents ($x **= 10)

% = Modulus ($x %= 10)

/ = Division ($x /= 10)Arithmetic Operators Assignment Operator

Operator Use

&&, and Associates two variables using AND

||, or Associates two variables using OR

Logical Operator

Page 12: CGI With Object Oriented Perl

Operator Use Syntax Result

==,eq Equal To 5 == 55 eq 5

True

!= ,ne Not Equal To 6 !=56 ne 5

True

< ,lt Less Than 7<47 lt 4

False

>,gt Greater Than 7>47 gt 4

True

<=,le Less Than Equal To 7<== 117 le 11

True

>=, ge Greater Than Equal To 7>=117 ge 11

FalseRelational Operators

Page 13: CGI With Object Oriented Perl

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.

Example: #!/usr/bin/perl print "content-type: text/html \n\n"; # DEFINE AN ARRAY @coins = ("Quarter","Dime","Nickel"); # PRINT THE WHOLE ARRAY print "@coins"; print "<br />"; print $coins[0]; #Prints the first element Quater print "<br />"; print $coins[1]; #Prints the 2nd element Dime

Elements can also be indexed backwards using negative integers instead of positive numbers.

print $coins[-1] #Prints the last element Nickel print $coins[-2]; #Prints 2nd to last element Dime

Page 14: CGI With Object Oriented Perl

qw Subroutine If the array you wish to build has more than 5 elements. Use this neat little

subroutine to remove the need for quotes around each element when you define an array.

Syntax: @coins = qw(Quarter Dime Nickel ….); Length of an Array Retrieving a numerical value that represents the length of an array is a two step

process. First, you need to set the array to a scalar variable, then just print the new variable to the browser as shown below.

Example @nums = (1 .. 20); print scalar(@nums)."<br />"; $nums = @nums; print "There are $nums numerical elements<br />"; # In both cases it prints 20

Page 15: CGI With Object Oriented Perl

Adding and Removing Elements from & to an Array

Example @solom = (“Manoj”,”Mukesh”,”Suresh); push(@solom, Ramesh); # Adds Ramesh to the end of the Array delete $solom [1]; # Removes the value on index 1 i.e. Mukesh

Methods use

push() adds an element to the end of an array.

unshift() adds an element to the beginning of an array

pop() removes the last element of an array

shift() removes the first element of an array.

Page 16: CGI With Object Oriented Perl

splice() Replacing elements is possible with the splice() function Syntax: splice(@array,first-element,sequential_length,name of new elements). Example @nums = (1..20); splice(@nums, 5,5,21..25); print "@nums"; Here in the above example the replacement begins after the 5th element, starting

with the number 6 in the example above. Five elements are then replaced from 6-10 with the numbers 21-25.

split() Transform a string into an array. The split function requires two arguments, first the

character of which to split and also the string variable.

Page 17: CGI With Object Oriented Perl

Example#!/usr/bin/perlprint "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";In the first example, the split was called at each hyphen. In the latter example thenames were split by a comma, allowing for the split to take place between each nameO/P : Rain Drops On Roses And Whiskers On Kittens

Larry David Roger Ken Michael Tom

Page 18: CGI With Object Oriented Perl

join() join() function to rejoin the array elements and form one long, scalar string. #!/usr/bin/perl print "content-type: text/html \n\n"; #HTTP HEADER # A COUPLE OF ARRAYS @array = ("David","Larry","Roger","Ken","Michael","Tom"); @array2 = qw(Pizza Steak Chicken Burgers); # JOIN 'EM TOGETHER $firststring = join(", ",@array); $secondstring = join(" ",@array2); # PRINT THE STRINGS print "$astring<br />"; print "$string";O/p: David,Larry,Roger,Ken,Michael,Tom

Pizza Steak Chicken Burgers

Page 19: CGI With Object Oriented Perl

Control Structures If / unless statements While / until statements For statements Foreach statements Last , next , redo statements && And || as control structures

Page 20: CGI With Object Oriented Perl

In PERL files are given a name, a handle, basically another way of saying alias. All input and output with files is achieved through filehandling. Filehandles are also a means by one program may communicate with another program.

Assigning Handles A filehandle is nothing more than a nickname for the files you intend to use in your

PERL scripts and programs. A handle is a temporary name assigned to a file. Example #!/usr/bin/perl print "content-type: text/html \n\n"; $FilePath = “/export/home/bray/test.html" open(HANDLE, $FilePath, O_RDWR) or die "$filepath cannot be opened."; printf HANDLE "Welcome to TCS!"; close (HANDLE); die Function

It is used to kill your scripts and helps pinpoint where/if your code is failing

Assigning The handle

Page 21: CGI With Object Oriented Perl

Open A File #!/usr/bin/perl print "content-type: text/html \n\n"; #The header $FH = "filehandle"; $FilePath = "myhtml.html"; open(FH, $FilePath, permissions); or sysopen(FH, $FileName, permission); Permission

Opening The File

O_RDWR Read and Write

O_RDONLY Read Only

O_WRONLY Write Only

O_CREAT Create the file

O_EXCL Stops if file already exists

O_APPEND Append the file

O_NONBLOCKNon-Blocking usability

Page 22: CGI With Object Oriented Perl

Following the example above when we called our HTML file handle using the inputoperator, PERL automatically stored each line of the file into a global array.#!/usr/bin/perlprint "content-type: text/html \n\n"; #The header$HTML = "myhtml.html";open (HTML) or die "Can't open the file!";@fileinput = <HTML>;print $fileinput[0];print $fileinput[1];print $fileinput[2];print "<table border='1' align='center'><tr><td>Dynamic</td><td>Table</td></tr>";print "<tr><td>Temporarily Inserted</td><td>Using PERL!</td></tr></table>";print $fileinput[3];close (HTML);

Page 23: CGI With Object Oriented Perl

Remove a File Remove Multiple Files

#!/usr/bin/perl

print "content-type: text/html \n\n";#The header$file = "newtext.txt";if (unlink($file) == 0) { print "File deleted successfully.";} else { print "File was not deleted.";}

#!/usr/bin/perl

print "content-type: text/html \n\n";#The header@files = ("newtext.txt","moretext.txt","yetmoretext.txt");foreach $file (@files) { unlink($file);}

Page 24: CGI With Object Oriented Perl

Compile /usr/bin/perl –wc <code.pl> Execute ./code.pl

08/05/10Document Owner : BUNTY RAY