Day 1



PERL: Practical Extraction and Reporting Language

It is general purpose interpreter language. It is cross platform language i.e. it uses same syntax in UNIX & Windows environment.
Perl is extended from Unix Shell + SED + AWK. 
Shell is completely command oriented but Perl is sub-routine (Function) oriented.


Ex: grep, find are command used in UNIX but they are used as functions in PERL.

Perl supports Two way programming:
1. Procedure based
2. Object Oriented Programming

Following topics we will be discussing under Procedure based:
Data Structure
Operators (arithmetic, relational, logical, file)
Conditional Statement
Loops
File Handling
RegX
Functions
Reference (C pointer kind style, its new concept.)
Complex Data Structure
Package
Modules

Following topics we will be discussing under  OOPS based:
In-build modules
CPAN
DBI
CGI


Getting Started with PERL
Lets learn few basic commands that we will be using very frequently while programming the perl script.

How to find the current version of Perl:
$ perl –v
This is perl, v5.8.8 built for i386-linux-thread-multi
Copyright 1987-2006, Larry Wall

How to find the library path for PERL:
$ perl -V
Summary of my perl5 (revision 5 version 8 subversion 8) configuration:
………………………………………………………………………………………………………………………..
………………………………………………………………………………………………………………………..
………………………………………………………………………………………………………………………..
  Compiled at Oct 29 2012 02:55:50
  @INC:
    /usr/lib/perl5/site_perl/5.8.8/i386-linux-thread-multi
    /usr/lib/perl5/site_perl/5.8.8
    /usr/lib/perl5/site_perl
    /usr/lib/perl5/vendor_perl/5.8.8/i386-linux-thread-multi
    /usr/lib/perl5/vendor_perl/5.8.8
    /usr/lib/perl5/vendor_perl
    /usr/lib/perl5/5.8.8/i386-linux-thread-multi
    /usr/lib/perl5/5.8.8
  .
The above path is the path from where the perl interpreter will check for the .pl files to be interpreted.

How to interpret a PERL script?
perl <file name>.pl
How to find the location of PERL binary?We can use type command in UNIX systems to locate the PERL binaries.

How to import the PERL libraries in script:
If you are attempting to write your perl script, the binaries should be imported from the PERL location using TYPE command as shown above. 

The first line of the PERL script should be the location of the PERL binary prefixed with #! as shown below:
#!/usr/bin/perl 

How to find path of PERL library :
The location of the PERL library can found using WHEREIS command as shown below:


Using PRINT function in PERL:
syntax: print "arg1","arg2",.....

The print function in PERL script can take multiple arguments separated by a comma. It prints the arguments provided followed by the print statement.
examples of print function in PERL:
print “Test print function\n”;
print  “Test print function”,“\n”;
print `date`,”\n”;
print “Today:”,`date +%D`,”\n”;
print(“Sample text  \t  test text \n”);
Open and closed parenthesis is optional for all functions in PERL.

To comment any line in PERL:
For single line:
use # at the beginning of the line similar to UNIX shell script style.
For Multi-line Comment:
=begin
…………………….
…………………….
=cut

Second Method for multi-line command:
=head
…………………….
…………………….
=cut

Line Oriented Control: 
<<ABC;
Text
Text
Text
Text
Text
ABC
Here ABC is just a custom flag name.


Data Structure:
Since PERL is an interpreter, here we don't need to define primitive data types such as integer, characters, floating point etc similar to UNIX shell scripting. 

The data types in PERL can be categorized into 3 major types:
1. Scalar -> $ (prefix) -> Single Value (such as integer, char, string, floating point etc..)
2. Array -> @ (prefix) -> Collection of scalars, ordered list
3. Hash -> % (prefix)   -> Collection of scalars, unordered list

 
Defining/Declaring a variable:
While defining the variables their symbols are prefixed before the variable name.
<Data type symbol> <Variable Name>=<Values>;
 

eg:
$scalar_var="This is a scalar variable";
@array_var=("This is an array","multiple values");

PERL Program example: Demonstrating the use of SCALAR Variables in PERL. 
#============================================================================ #Example1: Using the Scalar variables
#============================================================================
#!/usr/bin/perl
#this is an example for Scalar variable declaration
#declaring and assigning the values to variables
$EMPID =1234;
$EMP_NAME="Ravi Ranjan";
$DEPT="Development Team";
$PLACE="Bangalore";
$Salary="50000\$";
#Printing the values of the variables.
print "------------Details for Mr. $EMP_NAME------------\n";
print "EMP_NAME: $EMP_NAME\n";
print "EMP_ID : $EMPID\n";
print "DEPT: $DEPT\n";
print "PLACE: $PLACE\n";
print "Salary: $Salary PM\n";
#============================================================================
 
Diamond (<>) operator:
It is used to read the data from the console/keyboard.
For reading data from keyboard
We should use <> operator
Syntax:
$<variable name>=<STDIN>;

 

chomp() function : 
chomp function is used to remove the \n(new line character) from the input variable. If you want to get input and removing the \n in single line use, following will be helpful:
chomp(<input variable>=<>)

PERL Program example: Demonstrating the use of diamond operator for taking input from console.

#===============================================================

#Example2: Reading data from the console
#===============================================================
 #!/usr/bin/perl

print "Enter the name: ";
$name=<>;
chomp($name);
print "Enter the working place for $name:";
chomp($place=<>);
print "The working place for $name is $place";

#===============================================================
 


Standard Mathematical Operators in PERL:
PERL supports standard mathematical operators +,-,*,/,% and **(exponent).


PERL Program example: Demonstrating the use of operators

#===============================================================  
#Example3: Demo for the usage of the operators
#=============================================================== 

#!/usr/bin/perl
#Example for the Arithmetic Operator
#Addition Operator
print "Enter the value for Var1 & Var2\n";
chomp($v1=<>);
chomp($v2=<>);
$sum=$v1+$v2;
print "Total sum of $v1 + $v2 is : $sum" ;

#Increment operator
print "A. $sum\n";
print "B. ++$sum\n";
print "C. ",++$sum,"\n";
print "D. $sum\n";

#String operator . is used for string concatenation
$FNAME="Ravi";
$LNAME="Ranjan";
$NAME="$FNAME "."$LNAME";
print "Name is : $NAME\n";

#For displaying string multiple times, here displaying name three times
print "$NAME "x3,"\n";
#=============================================================== 


Relation operators in PERL:

For Numbers:

OperatorMeaning
>Greater than
>=Greater than equal to
<Less than
<=Less than equal to
==Equal to
!=Not equal to

For Strings:
OperatorMeaning
gtGreater than
geGreater than equal to
ltLess than
leLess than equal to
eqEqual to
neNot equal to

 Example 4: Usage of Relational and logical operators

#===============================================================  #Relational Operator
<<ABC;
For String we use the operators eq (for equal) and ne (for not equal).
For Numerics we use ==, <, >, <=, >=, !=
ABC
print "Enter the value for N: ";
chomp($N=<>);
if($N<10)
{
                print "$N is less than 10..\n"
}
else
{
                print "$N is more than 10..\n"
}
print "TRUE BLOCK..$N\n" if($n<10);
#Calculating average and total of a student
print "Enter the student's name: ";
chomp($name=<>);
print "Enter the marks for 3 subjects: ";
chomp($s1=<>);chomp($s2=<>);chomp($s3=<>);
$total=$s1+$s2+$s3;
$avg=$total/3;
print "
Name: $name
Sub1: $s1
Sub2: $s2
Sub3: $s3
-------------
Total: $total
-------------
AVG: $avg
================================================\n";

#Logical Operators
<<DEF;
&&/and can be used for logical AND operator
||/or can be used for logical OR operator
! can be used for not operator
DEF

if($s1<50||$s2<50||$s3<50)
{
                print "$name is FAIL\n";
}
else
{
                print "$name is PASS\n";
}
============================================================================
Example5:  Nested IF ELSE Example
============================================================================
print "Enter the business enquiry number: ";
chomp($eno=<>);
if($eno<550 and $eno>500)
{
                print "Enter the quotation number: ";
                chomp($qno=<>);
                if($qno>600 && $qno<650)
                {
                                print "Enter the vendor name: ";
                                chomp($vname=<>);
                                if($vname eq "XEROX" or $vname eq "IBM")
                                {
                                                print "Enter the PO number:";
                                                chomp($pno=<>);
                                                if($pno>100 && $pno<150)
                                                {
                                                                print "The vendor details are as follows:\n";
                                                                print "==================================\n";
                                                                print "Vendor Name: $vname\n";
                                                                print "Business Enq. No.: $eno\n";
                                                                print "Quotation number: $qno\n";
                                                                print "PO No.: $pno\n";
                                                                print "Vendor Name: $vname\n";
                                                }
                                                else
                                                {
                                                                print "Enter the PO number between 100-150";
                                                }
                                }
                                else
                                {
                                                print "Enter the vendor name as IBM or XEROX\n";
                                }
                }
                else
                {
                                print "Enter the Quotation number between 600-650\n";
                }
}
else
{
                print "Enter the business enquiry number between 500-550\n";
}
============================================================================
Example 6: IF ELSIF Demo
============================================================================
print "Enter the value of V1: ";
chomp($v1=<>);
print "Enter the value of V2: ";
chomp($v2=<>);

if($v1 == $v2)
{
                print "The value of v1 and v2 are equal\n";
}
elsif($v1 > $v2)
{
                print "The value of v1 is greated than v2\n";
}
else
{
                print "The value of v1 is less than v2\n";
}
============================================================================
Example 7: IF ELSIF Demo
============================================================================
#!/usr/bin/perl/
print "+++++++++++++++++++++++MENU LIST+++++++++++++++++++++++\n
1. Working OS Version \n
2. Virtual Memory \n
3. CPU Load balance \n
4. Date \n
5. Mounted FS \n";

print "Enter your choice: ";
chomp($c=<>);

if($c==1)
{
        print `uname -a`;
}
elsif($c==2)
{
        print `vmstat`;
}
elsif($c==3)
{
        print `uptime`;
}
elsif($c==4)
{
        print `date`;
}
elsif($c==5)
{
        print `df -h`;
}
else
{
        print "Invalid Option!!";
}
============================================================================
 Unless(condition)
{}
else
{}
This is reverse logic of IF statement.

File Operators:
1. Regular File    -f
2. Directory         -d
3. link                    -l
4. char                   -c
5. Block                 -b
6. Pipe                  –p
7.  Socket             –s
8. read                  -r
9. write                 -w
10. Execute         -x
11. exists             -e
============================================================================
Example 8: Checking File Type.
============================================================================
$ perl 8.pl
Enter a file name: tes
File does not exists!!
$ perl 8.pl
Enter a file name: 7.pl
File: 7.pl is Regular File
$ clear
$ cat 8.pl
#!/usr/bin/perl/
print "Enter a file name: ";
chomp($name=<>);
if (-e $name)
{
        if (-f $name)
        {
                print "File: $name is Regular File\n";
        }
        elsif (-d $name)
        {
                print "File: $name is a directory\n";
        }
        else
        {
                print "File: $name is not a regular File\n";
        }
}
else
{
print "File does not exists!!\n";
}
============================================================================
Define Function: define function returns 1 if the variable contains a value else it does not return anything. IT is used for the input validation purpose.
$var1="A";
$var2;
print "Defined: ",defined($var1),"\n";
print "Defines:",defined($var2),"\n";
============================================================================
Length function: Count the number of characters for the scalar variables.
$var=”UNIX OS Concepts”;
print “A.\$var: ”,length($var),”\n”;
print “B. : ”,length(“AB”),”\n”;
============================================================================
Loops:
for
foreach
while
do…while
until
============================================================================ Example11: for loop example
============================================================================
for( $a = 10; $a < 20; $a = $a + 1 ){
    print "value of a using c style loop: $a\n";
}

for $a (10,11,12,13,14,15)
{
                print "Value of a using list: $a\n";
}

foreach $a (10,11,12,13,14,15)
{
                print "Value of a using foreach: $a\n";
}

for $i (`find ~ -type f –maxdepth 3`)
{
                print "$i";
}
#using default variable $_
foreach (10..15)
{
                Print "Hello..$_ ";
}

foreach (A..E)
{
                Print "Hello..$_ ";
}

foreach(a..e)
{
                Print "Hello..$_ ";
}
#Infinite Loop
for(;;)
{
print “Hello ”;
last; #like break               
}
Difference between unless and until statement:
Unless is looping statement and until is conditional statement.  So Unless will execute more than one time whereas until will execute only once.

$_ is in-built scalar variable. It is used for repetitive tasks.
for (unix, linux, win)
{
print "$_\n"
}
This will print the unix , linux and win in new lines
for (mon,tue,wed,thu,fri)
{
                if ($_ eq wed)
                {
                last;
                }
}
============================================================================
Arrays:
Arrays are declared with prefix @.
@os_array=(unix,linux,mac,win);
@os_array=();

To access the array or assign the value to a particular index use like os_array[2].
The size of array depends on the virtual memory size.
============================================================================ Example 12: Demo for usage of arrays
============================================================================
#Array Demo
@os=(unix,linux,mac,win);
print "1.@os\n";
print "2.$os[1]\t$os[2]\n";
for (@os)
{
                print "$_\n";
}
@os_name=@os;
$var=@os #this assigns the size of array to the scalar variable
print "Size of array is :",scalar($os),"\n";
============================================================================
scalar function can be used to print the size of the array.

No comments:

Post a Comment