Posted by : Unknown Tuesday, May 14, 2013

                                                PERL 
       (PRACTICAL EXTRACTION AND REPORT LANGUAGE)

1.INTRODUCTION:-

1.1 Internet programming languages: -

  Internet programming was given a boost with the advent of WWW to satisfy the demand for Internet based applications, which grew manifold. This application requires a language for their development. These languages were required to provide dynamic and an interactive content to static web pages. The client /server model was the obvious choice for Internet applications.
          In client server model the client sends request to the server, the server doesn’t have the capability to process the client requests. So, it internally contacts CGI to process the client request. The CGI process the client request and sends the response back to server. Now, the server sends the response to the client in the form of HTML page.
2.CGI (COMMON GATEWAY INTERFACE): -

          The common gateway Interface (C.G.I) is a specification defined by the World Wide Web consortium, defining how a program interacts with a Hyper Text Transfer Protocol (HTTP) server. The CGI provides middleware between www servers and external databases and information sources. 

2.1 WHY IS CGI USED: -

          The interactive web pages, that displays some present information. These interactive web pages enable a client to send information to the web server and get back a response that depends on the input.
          To create an interactive web page, HTML elements are used to display a form that accepts a client's input and passes this to special computer programs on the web server. These computer programs process a client's input and return requested information. These programs are known as gateways because they typically act as a conduit between the web server and an external source of information such as database.

2.2 COMMON USES OF CGI: -

==>Gathering user feedback about a product line through an                               
        HTML form.
==>Querying an oracle database and rendering the result as an  
        HTML SSdocument.

2.3 PROCESS OF CGI: -

          ==>A client makes an HTTP request by means of a URL. This URL could be typed into the 'location' window of a browser.
          ==>From the URL, the web server determines that it should active the gateway program listed in the URL.
          ==>The gateway program processes the information and returns HTML text to the web server. Then it returns HTML text to web browser.
          ==>The web browser displays the document received from the web server.

2.4 HOW INFORMATION IS TRANSFERRED FROM THE WEB BROWSER TO A CGI PROGRAM: -
         
The web browser uses the method attribute of the <form> tag to determine how sends the form's data to the web server. There are two submission methods: GET and POST.

GET=>>The web browser submits the form's data as a part of a URL. The GET command sends a URL to the web server. If the form's data is sent to the web server using the GET command, the browser must include all data in the URL.

POST=>>The web browser sends the form's data separately from the URL as a stream of bits. In the POST method, the web browser sends the POST command to the server and includes the form's data in the body of that command. The POST method can handle any amount of data.

2.5 WHY IS PERLFOR CGI? : -
           
A CGI program can be written in any language like c, c++, VBscript, perl, TCL, REXX, python, Icon, Applescript, Unix shell scripting. But PERL is especially suited for this because perl programs are easy to learn and write. PERL is a scripting language, which means it does not have to be compiled. Instead, an interpreter executes the perl script, this makes it easy to write and test PERL scripts, because they do not have to go through the typical edit-compile-link cycles.

3. INTRODUCTION TO PERL:-

3.1 HISTORY OF PERL: -

         Developed by "Larry Wall" basically on UNIX systems. The basic reason for developing PERL is it gives much flexibility in string manipulations. PERL is an acronym for "Practical Extraction and Reporting Language". It was originally created to extract information from text files and then use that information to prepare reports.
         Perl has gained recent attention in the explosion of the W.W.W as a quick and effective way to mock up applications that provide much of the web's interactivity. It has a lot of syntax that can make scripts contain more characters from the top row or the keyboard then any other, but that is not necessary to get anything done. In fact there are few of the traditional limitations that interpreted language impose.

3.2 FEATURES OF PERL: --

           --->PERL is case sensitive language.
           --->PERL is freeform language.
           --->Each PERL statement must end with a semicolon (;).
           --->Comments begin with hash mark (#).
           --->A group of PERL statements can be treated as a block            by enclosing them in braces ({…}).
           --->It is interpreted based language.
           --->It is a scripting language.
           --->String manipulations are very easy.
           --->Code optimization.

3.3 STRATEGY: -

Strategy for this seminar is to establish the basics of perl. The script we'll be useful to anyone who has wanted to create some interactive pages on the World Wide Web.  Web servers usually support running auxiliary programs to facilitate interactive content. There is standard called C.G.I, which defines a minimum set of environment variables that the program can use to determine its response.
     The program we write will take the results of an HTML form and mail the values to a specified person. Writing the HTML for this form is beyond the scope of this seminar, but a sample form be provided.
       The beauty of this program is that any user on the web server can use it to response to their forms. You don't need to give everyone access to your server configuration. Users will enable themselves for this program, and then can write arbitrary forms from anyone on the web to fill out.

4.VARIABLES IN PERL:-
         
Variables are used to store data. In PERL each variable has a name and can store any type of data. Each variable name in PERL begins with special character. There are five special characters are used in PERL.

                              *  A dollar ($) sign
                              *  An at (@) sign
                              *  A percent (%) sign
                              *  An ampersand (&) sign
                              *  A less than greater than (<>) symbol

          Special character denotes the variable type. There are five types of variables available in PERL language.
         
                             *  Scalar variables
                             *  Indexed Array variables
                             *  Associative Array variables
                             *  Subroutine
                             *  File handler

            In PERL, there is no data type for a variable. The sex or data type of the variable is dependent on the context in which it is used.

4.1 SCALAR VARIABLES: -

          A scalar variable can reference a string value or a numeric. We can identify these two by visible difference. If the value of the variable is surrounded in single of double quotes, then PERL treats the variable as a string. If there are no quotes, then PERL has to decide if the value is a string or a numeric value. These variables are preceded by the '$' sign.

                   $First name="Sanjay";
                   $Last name="Kumar";
                   $Age=23;

4.2 INDEXED ARRAY VARIABLES: -

          These arrays are indexed by only integer values. Indexed arrays are denoted by the '@' sign.
         
          Ex:-@months=("jan","feb","mar","apr","may","jun");
          Arrays are start at index 0. In the above example @months [0] will have a value Jan and @months [1] have Feb.

Extracting Information from an Indexed Array: -

          The 'qw' keyword is a shortened form used to extract individual words from a string. The most common method of extracting information from an array is to index the array elements directly.
          Ex: -@months=qw (Jan Feb mar apr may jun);
                 for($x=0; $x<=$#months; $x++)
                 {
                     Print "index [$x]=$months [$x] \n";
                  }

4.3 ASSOCIATIVE ARRAY VARIABLES: -

          These arrays are also called 'Hash' arrays. They are indexed by string values instead of by integer index values. These arrays are identified by  '%' sign.
          Ex: -%cities=("a","hyderabad","b","bangalore","c","chennai");
The above example can be rewritten as: -
                 $Cities {'a'}=Hyderabad;
                 $Cities {'b'}=Bangalore;
                 $Cities {'c'}=Chennai;

Extracting Information from an Associative array:-

          The contents of an associative array can be accessed using three PERL functions. They are: keys, values, each.
‘Keys’ function: -
          The keys function returns a list of the keys of the given associative array.
          Ex: -#! g:\perl\bin\perl
                 %Cities=("a","hyderabad","b","bangalore',"c","chennai");
                 for $key (keys% cities)
                 {
                    Print "key=$key \n";
                 }
'Values’ function: -
          The values function can be used to directly access the values in an associative array.
          Ex: -#! g:\perl\bin\perl
                %Cities=("a","hyderabad","b","bangalore");
                for $value (values %cities)
                {
                   Print "value=$value \n";
                 }
'Each’ function: -
          The each function returns a key-values pair from the associative array.
          Ex: -#! g:\perl\bin\perl
                %Cities=("a","hyderabad","b","bangalore");
                While (($key, value)=each% cities)
                 {
                    Print "key=$key value=$value \n";
                  }
4.4 SUBROUTINE DATA TYPES:-
          Subroutines are identified with an "&" symbol and subroutine name.
          Ex:
              $i=10;
              $j=20;
              $Large=&max ($i, $j);
                Print $large;
              Sub max
              {
                 My $max=shift (@_)
                 for each $arg (@_)
                 {
                    if ($max<$arg)
                    $Max=$arg;
                  }
                  return $max;
                }
5. ARITHMATIC&RELATIONAL  OPERATORS:-

     =>>Arithmetic operators are same as in the C language.
     =>>In some languages, relational operators are used to comparing numbers and also for text strings. But, PERL has a complete set of relational operators for comparing strings.
     
     Operator      Example           Description
           eq            $x eq $y             value is true if the strings $x and                                                             
                                                      $y are equal, else false.
           ne            $x ne $y           value is true if the strings $x and         
                                                      $y are not equal, else false.
           gt            $x gt $y                      value is true if $x is greater than
                                                       $y, else false.
           ge            $x ge $y             value is true if $x is greater than          
                                                       Or equal to  $y, else false.
            lt             $x lt $y                     value is true if $x is less than $y,
                                                       else false.
           le              $x le $y           value is true if $x is less than or
                                                       equal to $y, else false.
         cmp          $x cmp $y          value is -1 if $x is less than $y, 0
                                                       if the strings are equal and 1 if      
                                                       $x is greater than $y.
6. CONTROL  STRUCTURES:-

                   Only simple programs are executed strictly in linear order. More complex programs require that conditions be tested and acted upon appropriately some conditions will require that a statement or block of statements be executed over and over again a specified number of times, or until condition is met or satisfied.
        The basic control structures in perl are:
                1.if/else
               2.nested if/else
               3.unless
               4.while
               5.until
               6.do...while
               7.do...until
               8.for
               9.foreach

7.  FUNCTIONS IN PERL:-

7.1 String Functions: -

*  Chop () - chop cutoff's or removes the last character in the scalar         variable.
               Ex: -#! g:\perl\bin\perl
                    $line="I LIKE YOU";
                     Chop ($line);
                      Print “line";
          Out put is I LIKE YO.
*  Chomp () - Removes the new line character if it presents in the string.
*  Sub string () –Using this to extract some part of a string.
                      Syntax: -substr (string, offset, length)
Length () - It is used to find the length of the string.
              Ex:-$name="I LIKE YOU";
                    $Length=length ($name);

Split ()  - Based on the delimiter you can split the array.
                   Split (/#/, @x)         
                   Now @x=(10, "svccs", 4, "mca");

7.2 Array Functions: -

Shift ()  - Removes the first element from the array
                Ex: -#! g:\perl\bin\perl
                      @Cities=qw (H B C);
                      $delcity=shift (@cities);
                      Print "@cities";
                Output is- ("B","C")

Unshift ()  - Inserts the element at the first position of the array.
               Ex: -#! g:\perl\bin\perl
                     @Cities=qw (H B C)
                      Unshift (@cities,"M","O");
                      Print "@cities";
              Output is- ("M","O","H","B","C")
Pop ()  - Removes the last element from the array.
              Ex: -#! g:\perl\bin\perl
                    @Cities=qw (H B C);
                     $delcity=pop (@cities);
                     Print "@cities";
              Output is- ("H","B")
Push ()  - Inserts the element at the end of the array.
              Ex: -#! g:\perl\bin\perl
                    @Cities=qw (H B C);
                     Push (@names,"M","O");
                     Print "@cities";
             Output is- ("H","B","C","M","O")
Sort ()  - Based on the ASCII value the List will be sorted.
                  Syntax: -sort (@cities);
Reverse ()- List will be completely reversed.
          Syntax: -reverse (@cities);
* Splice () - Simple and complex function which gives you the
Multiple functionality against arrays. This function acts differently depending upon the no. of arguments passed.
                 By this function we can perform

           *  Delete       * Insert      *Replace    operations.
        If the number of arguments in splice function is 3 then it signifies the Delete operation.
        If the number of arguments in splice function is 4 then it signifies the either Replace or Insert operations.
        If the third parameter in the splice command is '0' then it signifies inserts operation else if the third parameter is other than '0' then it signifies Replace.

DELETE: -


Splice (@x, 0,1)             ---- Removes the first value.
Splice (@x, 1,3)             ---- Removes 3 elements starting from  
                                             Second position.
Splice (@x, $#x/2,2)      ---- Removes 2 elements from the middle
                                           Position.

INSERT: -

               $P="Hello World";
               Splice (@x, 0,0, $p)              
               Now @=(,"Hello World", 10, "svccs", 4, "mca");

REPLACE: -

$Val=100;
Splice (@x, 2,1, $val)              
                   Now @=(,"Hello World", 100, "svccs", 4, "mca");
*  Concatenation-The string concatenation operator is represented    by     a period (".").
                   Ex: -#! g:\perl\bin\perl
                          $First name="Sanjay";
                          $Last name="Kumar";
                          $Full name=$first name. $Last name;
                          Print "$full name";
                  Output is-sanjaykumar
Join()  -  We can join all the elements of the array.
                   Join ("#", @x)          
                   Now @x=(10# "SLNCS"# 4# "mca");

8. FILE HANDLERS:-

         In each and every language input and output both from standard devices and from disk files is important.
Perl sends data to output devices and receives data from i/p devices via I/O channels. The I/O channels are called file handles. File input from the keyboard and output to the printer, perl provides two file handles they are STDIN, STDOUT respectively. There is also a prenamed file handle for I/O errors, STDERR.
         
  The<STDIN > File handle:
                   When we want to get input from the user in perl programs we use the STDIN file handle. To get i/p from STDIN, you enclose the file handle with PERL'S operator for reading lines of text, the angle operator <>.
          Syntax: -$var=<STDIN>; # it reads only one line
                     @Var=<STDIN>; # it reads multiple lines
         

Ex: -#! g:\perl\bin\perl
                 While ($line=<STDIN>)
                  {
                     Print "$line";
                   Last if ($line eq "quit\n");
                   }

The < STDOUT >File handle:

                      For output to the standard output device the screen, perl uses the print function. Print takes two arguments, the file handle of the I/O channel being printed to, and a string or list of comma-separated strings. Formatted output can be obtained with printf function.
          Syntax: -print STDOUT "whatever you want to print";

Syntax for opening a file: 
              Open (file handler, name of file)
                   Open (fh,"abc.dat")  ------ opens file in read   mode.
                   Open (fh,">bac.dat") ------ opens file in write mode.
                   Open (fh,">>abc.dat") ------ opens file in append mode.
               Ex:  read.pl                         
                      Open (fh,"abc.dat");
                              $x=<fh>;
                              While ($x)
                              {
                                 Print  "$x","\n";
                                 $x=<fh>;
                              }
                Ex: write.pl
                               Print "Enter your name:";
                               $Name=<stdin>;
                               Chop ($name);
                               Print "Enter your age:";
                               $Age=<stdin>;
                               Chop ($age);
                               $d="#", $n="\n";
                               $Rec=$name. $d. $age.$n;
                               Open (fh,">wrec.dat");
                               Print fh  $wrec;
                              # Close (fh);

9. WORKING WITH DIRECTORIES:-

                   Directories are special files that contain information about the other directories and files. PERL provides several functions to access and use information in a directory.

To open a directory: -

                   For opening a directory, directory handle is set up and opendir () function is used.
                   Syntax:-opendir (DIRHANDLE,”dirname”);

To close a directory: -

                   The close () can be called to close the directory when it is no longer in use.
                   Syntax: -close (DIRHANDLE);

Creating a directory: -

                   The mkdir () is used to create a directory as in Unix. To create a directory calls the mkdir () with argument.
                   Syntax: -mkdir (“directory name”);

To remove a directory:-

                   To remove a directory calls the rmdir () with an argument. The rmdir () does not remove the directory if it contains any files.
                   Syntax: -rmdir (“directory name”);

To go to the beginning of the directory: -

To go beginning of the directory after having read  
Some of the entries. To do so, call the rewinddir ().
                   Syntax: -rewinddir (DIRHANDLE);

Reading the contents of the directory: -

                   After the directory is open, its contents can be read using the readdir (). For example, to read all the directory entries into an array with a single call to the redder functions.
                   Syntax: -@file list=readdir (DIRHANDLE);
10. DATABASE PROGRAMMING IN PERL:-
          Perl language provides many features for data base programming.
UNIX ENVIRONMENT:
          On many unix systems, there is a system database feature called this database lets you store information in key-value pairs.  In a pair of disk files  Perl provides access to this database through a hash that is associated with the DBM.  Via hash you can add data to DBM ,and edit and delete data in the DBM.
          The disadvantage in the DBM system is that it works only with a key value pairs,which occurs often.
            To store more complex data Random Access to Files is recommended.
WINDOWS ENVIRONMENT:
          In windows environment ,database programming is done using
Microsoft’s ActiveX Data Objects and Open Database Connectivity.
ActiveX Data Object is an interface that exposes a set of objects that provide access to Msaccess files, or SQL server.
          ODBC is a popular data access method that is implemented in perl  using win32::ODBC module.Using this module you can connect to any  ODBC compliant relational database.
 11. CONCLUSION:- 
Perl basically evolved for extraction and report generation operations. Due to its powerfulness it is widely used in string manipulations I/O and system tasks. Now perl is widely used for writing C.G.I scripts.


Leave a Reply

Subscribe to Posts | Subscribe to Comments

- Copyright © Seminar Sparkz Inc -- Powered by Semianr Sparkz Inc - Designed by Shaik Chand -