KEMBAR78
Perl | PPT
1
By
B.R.S.S.RAJU
Asst.Prof
Aditya Engineering College
Surampalem
2
Perl Introduction:
 Developed by Larry Wall in 1987.
 "Practical Extraction and Report Language".
 Text processing activity, automation and web applications.
 Perl is used for a variety of purpose including web development,
GUI development, system administration.
 Cross platform programming language.
 Extension for PERL program is “.pl”.
Features:
It takes the features from C, sed, awk, sh.
Includes powerful tools to process text to make it compatible with
mark-up languages like HTML, XML.
 Supports third party database including Oracle, MySQL and many
others. (Database integration using DBI CPAN module).
 offers a regular expression engine which is able to transform any
type of text.
 case sensitive.
 Perl is an interpreted language.
3
Contents:
 Basic i/o statements
 Data types.
 Scalars expressions (Operators)
 Control structures
 Arrays
 Hashes
 lists
 Patterns and Regular expressions
 Subroutines
4
I/O statements:
Input:
Perl STDIN
syn: $varible= <STDIN>;
eg: $name = <STDIN>;
Output :
Print():
Syn: print “ “;
Eg: print "Welcome to IV CSE n“;
# Program to find area of square
print "Enter value for Side:";
$side=<STDIN>;
$area=$side*$side;
print "Area is:$arean";
5
Data types:
3 types of data types
scalar ($)
 array (@)
hashes (%)
Sample Program:
# Demo on Data types
$name="Ravi";
@skills=("Ravi",1,"Shankar",2,"chaitu",4);
%exp=(101=>4,102=>5);
print "$namen";
print @skills,"n";
print %exp;
6
Variables:
Declaration: equal sign (=) is used to assign values to
variables
$variable=value.
Sample Program:
#Demo on variables
$name = "Anastasia";
$rank = "9th";
$marks = 756.5;
print "The details are:n Name:$namen Rank:$rankn Marks:$marks";
7
Variables cont...
It should start with “$”.
We can perform arithmetic operations.
Concatenation operator. (Dot (.) or comma is used for
concatenating strings.
Repetition operator. (x is used for repeating the scalar)
 Eg: $scalarnum x 5;
vstrings (scalar declaration using ASCII numbers)
Sample Program:
#Numeric Scalar
$numScalar=100;
#String Scalar
$strScalar='Perl';
#vString
$vString=v85.78.73.88;
print $numScalar."-".$strScalar."-".$vString."n";
print "=" x 10,"n";
8
Arrays:
An array is a list of having scalars of any data type.
Array is created with the symbol “@” (or) qw.
Elements can be accessed by index numbers starting from 0 or by
using the range operator (….)
Array size can be known by 2 ways:
Scalar @<Array name>
$# Array name +1.
9
Functions to modify an array:
push ( ): Appends an element at the end of array.
Syn: push (@<array name>, <element>)
unshift ( ): Appends an element at the starting of array.
Syn: unshift (@<array name>, <element>)
pop ( ): Removes an element at the end of array.
Syn: pop (@<array name>)
shift ( ): Removes an element at the starting of array.
Syn: shift (@<array name>).
10
Slicing and Splicing of array:
Slicing:
Extracting elements with indexes from an array.
Syn: @<Array name> [...]
Splice:
Replace elements.
Remove elements from last.
Syn: splice(@<Array Name>,OFFSET, Length, List)
11
Split and Join:
Split:
Convert string to an array depending on a delimiter.
Syn: split(“Delimiter”, <String>);
Join:
Converts array to string
Syn: join(“Delimiter”,@<Array Name>);
12
Sorting Array,$[ and Merging:
Sort:
sort () function sorts an array based on ASCII.
Syn: sort (@<Array Name>)
$[:
modify the first index number of an array.
syn: $[=number
Merging: 2 or more arrays can be merged.
Syn: ( @<Array1>,@<Array2>)
13
Hashes:
1. Hash is set having key & value pairs.
2. “% “ symbol used to create a hash
syn: %<hash name>=(key1=>value, key2=>value);
3. Accessing Value from key
syn: $<hash name>{<key>};
4. Extract keys from hash
Syn: keys%<hash name>;
5. Extract values from hash
syn: values%<hash name>;
14
Hash cont...
6. Exists(): To check whether key exists in a hash (or) not.
syn: exists $<hash name> { key};
7. Hash Size: Extract keys /values in to an array and then get the
size.
8. Adding key value pair.
Syn: $<hash name>{<key>}=<value>;
9.Deleting a Pair
Syn: delete $<hash name>{<key>};
15
Scalars:
1. Scalar is a variable which can hold a single unit of data such as
integer, string, float etc.
2. No need to mention the data type.
3. Depending on the value it is holding it is termed as numeric
scalar, string scalar, float scalar etc.
Declaration:
1. It should start with “$”;
eg: $ sname=“Ravi Shankar”;
$ eid=2210;
$ savg=72.5
16
Scalars Cont....
2. We can perform Arithmetic operations (+,/).
3. Concatenation operator (.) dot or (,) comma is used for
concatenating strings.
4.Repetion operator
X is used for repeating the scalar.
Eg: $ scalarnum x 5
5. Vstrings : scalar declaration using ASCII Numbers.
17
Scalar Expressions:
Scalar data items are combined into expressions using operators.
Arithmetic operators
Numeric Relational Operators
String Relational Operators
Assignment Operators
Logical Operators
Quote Like Operators
18
Arithmetic operators:
The arithmetic operators are of 6
types
•Addition  (+)
•Subtraction  (-)
•Multiplication  (*)
•Division  (/)
•Modulus  (%)
•Exponent  (**)
Sample Program:
use strict;
use warnings;
my $n1=10;
my $n2=2;
my $sum= $n1+$n2;
my $diff=$n1-$n2;
my $product=$n1*$n2;
my $quo=$n1/$n2;
my $rem=$n1%$n2;
my $expo=$n1**$n2;
print "Sum=$sumn Difference=$diffn
Product= $product n Quotient=$quo n
Remainder=$rem n Exponent=$expon“;
19
Numeric Relational Operators:
Numeric Relational operators are of 7
types
Equal to  (==)
Not equal to  (! =)
Comparison  ( < = >)
Lessthan  (<)
Greaterthan  (>)
Lessthan Equal to  (<=)
Greaterthan Equal to  (>=)
Sample Programs:
use strict;
use warnings;
my $n1=29;
my $n2=20;
print "Equals to:",$n1==$n2,"n";
print "Not Equals to:",$n1!=$n2,"n";
print "Lessthan:",$n1<$n2,"n";
print "Greaterthan:",$n1>$n2,"n";
print "Greaterthan or equal
to:",$n1>=$n2,"n";
print "Lessthan or equal
to:",$n1<=$n2,"n";
print "Comparison
operator:",$n2<=>$n1,"n“;
20
String Relational Operators:
7 types of string relational
operators
Equal to  (eq)
Not equal to  (ne)
Comparison  (cmp)
Lessthan  (lt)
Greaterthan  (gt)
Lessthan Equal to  (le)
Greaterthan Equal to  (ge)
Sample Program:
use strict;
use warnings;
my $str1="python";
my $str2="Perl";
print "For Equal to:",$str1 eq $str2,"n";
print "For Not Equal to:",$str1 ne $str2,"n";
print "For Comparison:",$str1 cmp $str2,"n";
print "For Lessthan:",$str1 lt $str2,"n";
print "For Greaterthan:",$str1 gt $str2,"n";
print "For Lessthan Equal to:",$str1 le $str2,"n";
print "For Greaterthan Equal to:",$str1 ge
$str2,"n“;
21
Assignment Operators:
Uses the symbol “=”
+= Adds right operand to left.
 -= Subtracts right operand from left.
*= Multiplies right operand to the left.
/= Divides left operand with the right.
%= Modules left operand with right.
**= Performs Exponential.
. = Concatenates right operand with left
operand.
Sample Program:
use strict;
use warnings;
my $no1=5;
my $no2=2;
$no1+=$no2;
print "sum:$no1n";
$no1.=$no2;
print "concatenate:$no1n";
$no1-=$no2;
print "Diff:$no1n";
$no1*=$no2;
print "Product:$no1n";
$no1/=$no2;
print "Quotient:$no1n";
$no1%=$no2;
print "Remainder:$no1n";
$no1**=$no2;
print "Exponent:$no1n“;
22
Logical Operators:
Logical AND and
C-style logical AND &&
Logical OR or
C-style Logical OR ||
Not not
Sample Program :
use strict;
use warnings;
my @skills=("Perl","Python","Java","Unix");
if (( $skills[0] eq "Perl") and (scalar
@skills==4))
{
print "Logical AND operatorn";
}
if (( $skills[0] eq "Perl") && (scalar
@skills==4))
{
print "C-style Logical AND operatorn";
}
if (( $skills[0] eq "Python") or (scalar
@skills==4))
{
print "Logical OR operatorn";
}
if (( $skills[0] eq "Python") || (scalar
@skills==4))
{
print "C-style Logical OR operatorn";
}
if (not(( $skills[0] eq "Python") and
(scalar @skills==4)) )
{
print "Not Logical AND operatorn";
}
23
Quote Like Operators:
Single quote  q{}
Double quote qq{}
Bactics  qx{}
Array qw{}
Sample Program:
use strict ;
use warnings;
my $single=q{Perl};
my $double=qq{Perl};
print"$singlen$doublen“;
my @array=qw(Perl Python 2 3 4);
print "@arrayn";
24
Control Structures:
In PERL we have 7 different types of Decision conditioning
statements. They are
If
If ..else
If..elsif..else
Unless
Unless..else
Unless..elsif...else
Switch
Ternary operator  (condition)? <True> :<False>
25
Simple if:
simple if is same as in c ,c++ or in java. The statements in this
will be executed only the condition is true.
Syn: if (condition)
{
True block statements;
}
Sample Program:
use strict;
use warnings;
my @skills=("Perl", "Python", "Java", "Unix", "Shell");
if ($skills[-1] eq "Shell")
{
print "If ..Truen";
}
26
If..else :
Syn:
if (condition)
{
True Block;
}
else
{
False block;
}
Sample Program:
use strict;
use warnings;
my @skills=("Perl", "Python", "Java",
"Unix", "Shell");
if($skills[-1] eq "Java")
{
print "if..Truen";
}
else
{
print "Else..Truen";
}
27
If ..elsif..else:
Syn:
if(condition)
{
True block;
}
elsif(condition-2)
{
True block
}
else
{
False block;
}
Sample Program:
use strict;
use warnings;
my @technologies=("C","C++","Java",
"Dbms", "Python", "Perl");
if( $technologies[-1] eq "Java")
{
Print "if..True..n";
}
elsif($technologies[0] eq "C++")
{
print "else if..Truen";
}
else {
print "else...Truen";
}
28
Nested if:
Sample Program:
use strict;
use warnings;
my @names=("Ram", "Chaitu", "Manohar", "Vishnu");
if($names[-1] eq "Vishnu")
{
if($names[0] eq "Ram")
{
print "True!!n";
}
}
29
Unless :
Syn:
Unless(condition)
{
//statements of unless
}
Sample Program:
use strict;
use warnings;
my
@branches=("cse","ece","civil","mech","agri","eee");
unless(scalar @branches==5)
{
print "unless..Truen";
}
Note: unless is completely opposite to
simple if.
30
Unless..else:
Syn :
Unless(condition)
{
//statements of unless
}
else
{
// statements of else
part
}
Sample Program:
use strict;
use warnings;
my
@branches=("cse","ece","civil","mech","agri","eee");
unless(scalar @branches==6)
{
print "unless..Truen";
}
else
{
print "else..True!!n";
}
31
Unless..elsif..else:
Syn:
Unless(condition-1)
{
//statements of
unless condition-1;
}
Elsif(condition-2)
{
//statements of
unless condition-2;
}
Else
{
//Else part of
condition-2;
}
Sample Program:
use strict;
use warnings;
my
@branches=("cse","ece","civil","mec
h","agri","eee");
unless(scalar @branches==6)
{
print "unless..Truen";
}
elsif ($branches[-1] eq "agri"){
print "True!!n";
}
else{
print "else..True!!n";
}
32
Ternary operator:
Syn: (condition)? Statement1:statement2
Sample Program:
use strict;
use warnings;
print "Enter a user id: n";
my $input=<STDIN>;
chomp($input);
(length($input)==4) ? print "Length is 4n" : print "Length is not 4n" ;
33
Loops:
In PERL there are 7 different types of loops.
While loop
Do...while loop
Until loop
For loop
Foreach loop
While..each loop
Nested loops
34
While:
Sample Program:
use strict;
use warnings;
my @errors=("405-ERROR","100-
OK","101-OK","406-ERROR","102-
OK","503-ERROR","104-OK");
my $i=0;
my $count=0;
while($i <scalar @errors)
{
if($errors[$i]=~/ERROR/)
{
$count++;
}
$i++;
}
print "From while loop: $countn";
While:
Syn:
Initialization;
While(condition)
{
Increment/decrement;
}
35
Do-while:
Syn:
Initialization;
do
{
Increment/decrement;
} While(condition);
use strict;
use warnings;
my @errors=("405-ERROR","100-OK","101-
OK","406-ERROR","102-OK","503-
ERROR","104-OK");
my $i=0;
my $count=0;
do
{
if($errors[$i]=~/ERROR/){
$count++;
}
$i++;
} while($i<scalar @errors);
Print "From do..while loop: $countn“;
36
Until:
Sample Program:
use strict;
use warnings;
my @errors=("405-ERROR","100-OK","406-ERROR","102-0K","503-
ERROR","104-OK");
my $i=0;
my $count=0;
until($i > $#errors)
{
if($errors[$i]=~/ERROR/)
{
$count++;
}
$i++;
}
print "From until loop:$countn“;
37
for loop:
Sample Program:
use strict;
use warnings;
my @errors=("405-ERROR","100-OK","406-ERROR","102-0K",
"503-ERROR","104-OK");
print "Before Loop:@errorsn";
for (my $i=0; $i<scalar @errors;$i++)
{
if($errors[$i]=~/OK/)
{
my($errorCode,$msg)=split("-", $errors[$i]);
$errorCode++;
$errors[$i]="$errorCode-$msg";
}
}
print "After Loop:@errorsn";
38
for..each loop:
foreach loop can be used to iterate an array or hash.
Sample Program: (for each for array)
use strict;
use warnings;
my @skills=("Perl" ,"Python" ,"Unix" ,"Shell");
foreach(@skills)
{
print "$_n";
}
39
Regular expressions:
Regular expression is a way to write a pattern which describes
certain substrings.
1. Binding Operators:
=~//  To match a string.
Eg: $str=~/perl/
!=~//  Not to match a string.
Eg: $str=!~/perl/
2. Match regular expressions
Syn: /<Pattern>/ (0r) m/<Pattern>/
3. Substitute Regular Expression:
Syn: s/<matched pattern>/<replaced pattern>/
4. Transliterate regular expressions:
Syn: tr/a-z/A-Z/
40
my $userinput=“CSE Rocks";
if($userinput=~m/.*(CSE).*/)
{
print "Found Pattern";
}
else
{ print "unable to find the pattern";
}
my $a="Hello how are you";
$a=~tr/hello/cello/;
print $a;
my $a="Hello how are
you";
$a=~s/hello/cello/gi;
print $a;
my $var="Hello this is perl";
if($var=~m/perl/)
{
print "true";
}
else
{
print "False";
}
41
Sample Program:
use strict; re1.pl
use warnings;
my $str="I am student of Aditya Engineering College";
print "Before Changing:$strn";
# Matching of Pattern
if($str=~s/<Engineering>/<Engg>/)
{
print "After changing:$strn";
}
#Not Matching to a Pattern
if($str=!~/python/)
{
print "not Matchedn";
}
42
Sample Program: trans.pl
$str="I am student of Aditya Engineering College";
print "Before Changing:$strn";
if($str=~tr/Engineering/ENGINEERING/)
{
print "After Changing:$strn";
}
43
s Matches whitespaces {n,t,r}.
S Matches non whitespaces.
d Matches numbers.
D Matches non- numbers.
(.*) To retrieve the expressions matched inside the
parenthesis
^ Matches beginning of the line followed.
$ Matches end of the line
. Matches single character except newline
To match a new line use m//
[..] Any character inside square brackets.
[^..] Matches characters excluding inside the square
brackets.
* Matches 0 or more preceding expressions.
+ Matches 1 or more preceding expressions
? Matches 0 or 1 receding expressions.
44
{n} Matches n occurrences of preceding
expressions.
{n,} Matches n or more occurrences of preceding
expressions.
{n, m} Matches n to m occurrences of preceding
expressions.
n | m Matches n or m.
w Matches alphabetical characters.
W Matches non-alphabetical characters.
45
Complex Regular Expression:
Sample Program: re.pl
=head
com.W.tutorialspoint.C# 5.812345 AAA // *
com.X.tutorialspoint.C++ 6.815345 BBB // =
=cut
open(FHR,"test1.txt") or die "Cannot open file $!";
while(<FHR>)
{
if($_=~m{^com...w{14}.C(.*)[5-6].81[2 5]d{3}s+(AAA|BBB)(.*)[* =]$})
{
print "$_n";
}
}
close(FHR);
46
Subroutines:
Calling a subroutine:
Subroutine (arguments)
&subroutines(arguments) // previous versions
Passing arguments to subroutines:
Shift
$_[0],$_[1],..
@_
47
Returning values from subroutine:
“return” keyword is used to return values followed by a scalar
or a list.
48
Sample Program: subroutineex.pl
Use strict;
use warnings;
my @lines=("google.com 100","yahoo.com 101","microsoft.com
102","gitam.org 300","au.org 301","flikart.com 302");
sub displaycomlines{
foreach(@lines){
if($_=~/com/g){
print("$_n");
}
}
}
displaycomlines();
49
Sample Program with Single Parameter:
Use strict;
use warnings;
my @lines=("google.com 100","yahoo.com
101","microsoft.com 102","gitam.org 300","au.org
301","flikart.com 302");
My $msg=“org”;
sub displaycomlines{
foreach(@lines){
$msg=shift;
if($_=~/ $msg /){
print("$_n");
}
}
}
displaycomlines($msg);
50
Using SHIFT: (Double Parameter)
use strict;
use warnings;
my @lines=("google.com 100","yahoo.com 101","microsoft.com
102","gitam.org 300","au.org 301","flikart.com 302");
sub displaycomlines{
my $msg= shift;
my $code=shift;
foreach(@lines){
if($_=~/$msg.*$code/){
print "$_n";
}
}
}
displaycomlines ("com", 101);
51
Using Default Variable: (Double Parameter) subroutine4.pl
use strict;
use warnings;
my @lines=("google.com 100","yahoo.com 101","microsoft.com
102","gitam.org 300","au.org 301","flikart.com 302");
sub displaycomlines{
my $msg=$_[0];
my $code=$_[1];
foreach(@lines){
if($_=~/$msg.*$code/){
print "$_n";
}
}
}
displaycomlines ("com", 101);
52
Sample Program using @_ subroutine5.pl
use strict;
use warnings;
my @lines=("google.com 100","yahoo.com 101","microsoft.com
102","gitam.org 300","au.org 301","flikart.com 302");
sub displaycomlines{
my ($msg, $code)=@_;
foreach(@lines){
if($_=~/$msg.*$code/){
print "$_n";
}
}
}
displaycomlines("com",101);
53
Sample program how to pass an array to subroutine subroutine6.pl
use strict;
use warnings;
my @lines=("google.com 100","yahoo.com 101","microsoft.com
102","gitam.org 300","au.org 301","flikart.com 302");
sub appenddomain{
@lines=@_;
foreach(@lines)
{
if($_=~/com/){
$_.=": COM";
}
else{
$_.=": ORG";
}
};
return(@lines);
}
@lines=appenddomain(@lines);
print "@linesn“;
54
Sample program how to pass an hash to subroutine subroutine7.pl
use strict;
use warnings;
my %url=("google.com"=> 100,"yahoo.com"=> 101,"microsoft.com"=>
102,"gitam.org"=> 300,"au.org"=> 301,"flikart.com"=> 302);
sub appenddomain{
%url=@_;
foreach(%url)
{
if($_=~/com/){
$url{$_}--;
}
else{
$url{$_}-- ;
}
};
return(%url);
}
%url=appenddomain(%url);
print %url,”n”;
55
Sample Program to pass multiple data types to a subroutine subroutine8.pl
use strict;
use warnings;
my @lines=("google.com 100","yahoo.com 101","microsoft.com 102","gitam.org
300","au.org 301","flikart.com 302");
my %skillsandexperiences=(perl=>5,python=>2,unix=>5,java=>1);
my @skills=("perl","python","unix","java");
sub displaylines{
(@lines, %skillsandexperiences, @skills)=@_;
print "@linesn";
print %skillsandexperiences,"n";
print "@skillsn";
}
displaylines(@lines,%skillsandexperiences,@skills);
56
Strings:
String Operations:
Finding the Length of string.
Changing the case.
Concatenation (.).
Substring Extraction.
57
Sample Program:
use strict;
use warnings;
print "Enter first string:";
my $v1=< >;
print "Enter another string:";
my $v2=< >;
print "Upper case is:U$v1n";
print "Lower Case is:L$v1n";
my $v3= $v1.$v2;
print "Concatenated string:",$v3,"n";
print "Length of concatenated
string:",length($v3),"n";
print "Substring Extraction:",substr($v3,6,17);
print "Substring Extraction From
Last:",substr($v3,-5,6);
58

Perl

  • 1.
  • 2.
    2 Perl Introduction:  Developedby Larry Wall in 1987.  "Practical Extraction and Report Language".  Text processing activity, automation and web applications.  Perl is used for a variety of purpose including web development, GUI development, system administration.  Cross platform programming language.  Extension for PERL program is “.pl”.
  • 3.
    Features: It takes thefeatures from C, sed, awk, sh. Includes powerful tools to process text to make it compatible with mark-up languages like HTML, XML.  Supports third party database including Oracle, MySQL and many others. (Database integration using DBI CPAN module).  offers a regular expression engine which is able to transform any type of text.  case sensitive.  Perl is an interpreted language. 3
  • 4.
    Contents:  Basic i/ostatements  Data types.  Scalars expressions (Operators)  Control structures  Arrays  Hashes  lists  Patterns and Regular expressions  Subroutines 4
  • 5.
    I/O statements: Input: Perl STDIN syn:$varible= <STDIN>; eg: $name = <STDIN>; Output : Print(): Syn: print “ “; Eg: print "Welcome to IV CSE n“; # Program to find area of square print "Enter value for Side:"; $side=<STDIN>; $area=$side*$side; print "Area is:$arean"; 5
  • 6.
    Data types: 3 typesof data types scalar ($)  array (@) hashes (%) Sample Program: # Demo on Data types $name="Ravi"; @skills=("Ravi",1,"Shankar",2,"chaitu",4); %exp=(101=>4,102=>5); print "$namen"; print @skills,"n"; print %exp; 6
  • 7.
    Variables: Declaration: equal sign(=) is used to assign values to variables $variable=value. Sample Program: #Demo on variables $name = "Anastasia"; $rank = "9th"; $marks = 756.5; print "The details are:n Name:$namen Rank:$rankn Marks:$marks"; 7
  • 8.
    Variables cont... It shouldstart with “$”. We can perform arithmetic operations. Concatenation operator. (Dot (.) or comma is used for concatenating strings. Repetition operator. (x is used for repeating the scalar)  Eg: $scalarnum x 5; vstrings (scalar declaration using ASCII numbers) Sample Program: #Numeric Scalar $numScalar=100; #String Scalar $strScalar='Perl'; #vString $vString=v85.78.73.88; print $numScalar."-".$strScalar."-".$vString."n"; print "=" x 10,"n"; 8
  • 9.
    Arrays: An array isa list of having scalars of any data type. Array is created with the symbol “@” (or) qw. Elements can be accessed by index numbers starting from 0 or by using the range operator (….) Array size can be known by 2 ways: Scalar @<Array name> $# Array name +1. 9
  • 10.
    Functions to modifyan array: push ( ): Appends an element at the end of array. Syn: push (@<array name>, <element>) unshift ( ): Appends an element at the starting of array. Syn: unshift (@<array name>, <element>) pop ( ): Removes an element at the end of array. Syn: pop (@<array name>) shift ( ): Removes an element at the starting of array. Syn: shift (@<array name>). 10
  • 11.
    Slicing and Splicingof array: Slicing: Extracting elements with indexes from an array. Syn: @<Array name> [...] Splice: Replace elements. Remove elements from last. Syn: splice(@<Array Name>,OFFSET, Length, List) 11
  • 12.
    Split and Join: Split: Convertstring to an array depending on a delimiter. Syn: split(“Delimiter”, <String>); Join: Converts array to string Syn: join(“Delimiter”,@<Array Name>); 12
  • 13.
    Sorting Array,$[ andMerging: Sort: sort () function sorts an array based on ASCII. Syn: sort (@<Array Name>) $[: modify the first index number of an array. syn: $[=number Merging: 2 or more arrays can be merged. Syn: ( @<Array1>,@<Array2>) 13
  • 14.
    Hashes: 1. Hash isset having key & value pairs. 2. “% “ symbol used to create a hash syn: %<hash name>=(key1=>value, key2=>value); 3. Accessing Value from key syn: $<hash name>{<key>}; 4. Extract keys from hash Syn: keys%<hash name>; 5. Extract values from hash syn: values%<hash name>; 14
  • 15.
    Hash cont... 6. Exists():To check whether key exists in a hash (or) not. syn: exists $<hash name> { key}; 7. Hash Size: Extract keys /values in to an array and then get the size. 8. Adding key value pair. Syn: $<hash name>{<key>}=<value>; 9.Deleting a Pair Syn: delete $<hash name>{<key>}; 15
  • 16.
    Scalars: 1. Scalar isa variable which can hold a single unit of data such as integer, string, float etc. 2. No need to mention the data type. 3. Depending on the value it is holding it is termed as numeric scalar, string scalar, float scalar etc. Declaration: 1. It should start with “$”; eg: $ sname=“Ravi Shankar”; $ eid=2210; $ savg=72.5 16
  • 17.
    Scalars Cont.... 2. Wecan perform Arithmetic operations (+,/). 3. Concatenation operator (.) dot or (,) comma is used for concatenating strings. 4.Repetion operator X is used for repeating the scalar. Eg: $ scalarnum x 5 5. Vstrings : scalar declaration using ASCII Numbers. 17
  • 18.
    Scalar Expressions: Scalar dataitems are combined into expressions using operators. Arithmetic operators Numeric Relational Operators String Relational Operators Assignment Operators Logical Operators Quote Like Operators 18
  • 19.
    Arithmetic operators: The arithmeticoperators are of 6 types •Addition  (+) •Subtraction  (-) •Multiplication  (*) •Division  (/) •Modulus  (%) •Exponent  (**) Sample Program: use strict; use warnings; my $n1=10; my $n2=2; my $sum= $n1+$n2; my $diff=$n1-$n2; my $product=$n1*$n2; my $quo=$n1/$n2; my $rem=$n1%$n2; my $expo=$n1**$n2; print "Sum=$sumn Difference=$diffn Product= $product n Quotient=$quo n Remainder=$rem n Exponent=$expon“; 19
  • 20.
    Numeric Relational Operators: NumericRelational operators are of 7 types Equal to  (==) Not equal to  (! =) Comparison  ( < = >) Lessthan  (<) Greaterthan  (>) Lessthan Equal to  (<=) Greaterthan Equal to  (>=) Sample Programs: use strict; use warnings; my $n1=29; my $n2=20; print "Equals to:",$n1==$n2,"n"; print "Not Equals to:",$n1!=$n2,"n"; print "Lessthan:",$n1<$n2,"n"; print "Greaterthan:",$n1>$n2,"n"; print "Greaterthan or equal to:",$n1>=$n2,"n"; print "Lessthan or equal to:",$n1<=$n2,"n"; print "Comparison operator:",$n2<=>$n1,"n“; 20
  • 21.
    String Relational Operators: 7types of string relational operators Equal to  (eq) Not equal to  (ne) Comparison  (cmp) Lessthan  (lt) Greaterthan  (gt) Lessthan Equal to  (le) Greaterthan Equal to  (ge) Sample Program: use strict; use warnings; my $str1="python"; my $str2="Perl"; print "For Equal to:",$str1 eq $str2,"n"; print "For Not Equal to:",$str1 ne $str2,"n"; print "For Comparison:",$str1 cmp $str2,"n"; print "For Lessthan:",$str1 lt $str2,"n"; print "For Greaterthan:",$str1 gt $str2,"n"; print "For Lessthan Equal to:",$str1 le $str2,"n"; print "For Greaterthan Equal to:",$str1 ge $str2,"n“; 21
  • 22.
    Assignment Operators: Uses thesymbol “=” += Adds right operand to left.  -= Subtracts right operand from left. *= Multiplies right operand to the left. /= Divides left operand with the right. %= Modules left operand with right. **= Performs Exponential. . = Concatenates right operand with left operand. Sample Program: use strict; use warnings; my $no1=5; my $no2=2; $no1+=$no2; print "sum:$no1n"; $no1.=$no2; print "concatenate:$no1n"; $no1-=$no2; print "Diff:$no1n"; $no1*=$no2; print "Product:$no1n"; $no1/=$no2; print "Quotient:$no1n"; $no1%=$no2; print "Remainder:$no1n"; $no1**=$no2; print "Exponent:$no1n“; 22
  • 23.
    Logical Operators: Logical ANDand C-style logical AND && Logical OR or C-style Logical OR || Not not Sample Program : use strict; use warnings; my @skills=("Perl","Python","Java","Unix"); if (( $skills[0] eq "Perl") and (scalar @skills==4)) { print "Logical AND operatorn"; } if (( $skills[0] eq "Perl") && (scalar @skills==4)) { print "C-style Logical AND operatorn"; } if (( $skills[0] eq "Python") or (scalar @skills==4)) { print "Logical OR operatorn"; } if (( $skills[0] eq "Python") || (scalar @skills==4)) { print "C-style Logical OR operatorn"; } if (not(( $skills[0] eq "Python") and (scalar @skills==4)) ) { print "Not Logical AND operatorn"; } 23
  • 24.
    Quote Like Operators: Singlequote  q{} Double quote qq{} Bactics  qx{} Array qw{} Sample Program: use strict ; use warnings; my $single=q{Perl}; my $double=qq{Perl}; print"$singlen$doublen“; my @array=qw(Perl Python 2 3 4); print "@arrayn"; 24
  • 25.
    Control Structures: In PERLwe have 7 different types of Decision conditioning statements. They are If If ..else If..elsif..else Unless Unless..else Unless..elsif...else Switch Ternary operator  (condition)? <True> :<False> 25
  • 26.
    Simple if: simple ifis same as in c ,c++ or in java. The statements in this will be executed only the condition is true. Syn: if (condition) { True block statements; } Sample Program: use strict; use warnings; my @skills=("Perl", "Python", "Java", "Unix", "Shell"); if ($skills[-1] eq "Shell") { print "If ..Truen"; } 26
  • 27.
    If..else : Syn: if (condition) { TrueBlock; } else { False block; } Sample Program: use strict; use warnings; my @skills=("Perl", "Python", "Java", "Unix", "Shell"); if($skills[-1] eq "Java") { print "if..Truen"; } else { print "Else..Truen"; } 27
  • 28.
    If ..elsif..else: Syn: if(condition) { True block; } elsif(condition-2) { Trueblock } else { False block; } Sample Program: use strict; use warnings; my @technologies=("C","C++","Java", "Dbms", "Python", "Perl"); if( $technologies[-1] eq "Java") { Print "if..True..n"; } elsif($technologies[0] eq "C++") { print "else if..Truen"; } else { print "else...Truen"; } 28
  • 29.
    Nested if: Sample Program: usestrict; use warnings; my @names=("Ram", "Chaitu", "Manohar", "Vishnu"); if($names[-1] eq "Vishnu") { if($names[0] eq "Ram") { print "True!!n"; } } 29
  • 30.
    Unless : Syn: Unless(condition) { //statements ofunless } Sample Program: use strict; use warnings; my @branches=("cse","ece","civil","mech","agri","eee"); unless(scalar @branches==5) { print "unless..Truen"; } Note: unless is completely opposite to simple if. 30
  • 31.
    Unless..else: Syn : Unless(condition) { //statements ofunless } else { // statements of else part } Sample Program: use strict; use warnings; my @branches=("cse","ece","civil","mech","agri","eee"); unless(scalar @branches==6) { print "unless..Truen"; } else { print "else..True!!n"; } 31
  • 32.
    Unless..elsif..else: Syn: Unless(condition-1) { //statements of unless condition-1; } Elsif(condition-2) { //statementsof unless condition-2; } Else { //Else part of condition-2; } Sample Program: use strict; use warnings; my @branches=("cse","ece","civil","mec h","agri","eee"); unless(scalar @branches==6) { print "unless..Truen"; } elsif ($branches[-1] eq "agri"){ print "True!!n"; } else{ print "else..True!!n"; } 32
  • 33.
    Ternary operator: Syn: (condition)?Statement1:statement2 Sample Program: use strict; use warnings; print "Enter a user id: n"; my $input=<STDIN>; chomp($input); (length($input)==4) ? print "Length is 4n" : print "Length is not 4n" ; 33
  • 34.
    Loops: In PERL thereare 7 different types of loops. While loop Do...while loop Until loop For loop Foreach loop While..each loop Nested loops 34
  • 35.
    While: Sample Program: use strict; usewarnings; my @errors=("405-ERROR","100- OK","101-OK","406-ERROR","102- OK","503-ERROR","104-OK"); my $i=0; my $count=0; while($i <scalar @errors) { if($errors[$i]=~/ERROR/) { $count++; } $i++; } print "From while loop: $countn"; While: Syn: Initialization; While(condition) { Increment/decrement; } 35
  • 36.
    Do-while: Syn: Initialization; do { Increment/decrement; } While(condition); use strict; usewarnings; my @errors=("405-ERROR","100-OK","101- OK","406-ERROR","102-OK","503- ERROR","104-OK"); my $i=0; my $count=0; do { if($errors[$i]=~/ERROR/){ $count++; } $i++; } while($i<scalar @errors); Print "From do..while loop: $countn“; 36
  • 37.
    Until: Sample Program: use strict; usewarnings; my @errors=("405-ERROR","100-OK","406-ERROR","102-0K","503- ERROR","104-OK"); my $i=0; my $count=0; until($i > $#errors) { if($errors[$i]=~/ERROR/) { $count++; } $i++; } print "From until loop:$countn“; 37
  • 38.
    for loop: Sample Program: usestrict; use warnings; my @errors=("405-ERROR","100-OK","406-ERROR","102-0K", "503-ERROR","104-OK"); print "Before Loop:@errorsn"; for (my $i=0; $i<scalar @errors;$i++) { if($errors[$i]=~/OK/) { my($errorCode,$msg)=split("-", $errors[$i]); $errorCode++; $errors[$i]="$errorCode-$msg"; } } print "After Loop:@errorsn"; 38
  • 39.
    for..each loop: foreach loopcan be used to iterate an array or hash. Sample Program: (for each for array) use strict; use warnings; my @skills=("Perl" ,"Python" ,"Unix" ,"Shell"); foreach(@skills) { print "$_n"; } 39
  • 40.
    Regular expressions: Regular expressionis a way to write a pattern which describes certain substrings. 1. Binding Operators: =~//  To match a string. Eg: $str=~/perl/ !=~//  Not to match a string. Eg: $str=!~/perl/ 2. Match regular expressions Syn: /<Pattern>/ (0r) m/<Pattern>/ 3. Substitute Regular Expression: Syn: s/<matched pattern>/<replaced pattern>/ 4. Transliterate regular expressions: Syn: tr/a-z/A-Z/ 40
  • 41.
    my $userinput=“CSE Rocks"; if($userinput=~m/.*(CSE).*/) { print"Found Pattern"; } else { print "unable to find the pattern"; } my $a="Hello how are you"; $a=~tr/hello/cello/; print $a; my $a="Hello how are you"; $a=~s/hello/cello/gi; print $a; my $var="Hello this is perl"; if($var=~m/perl/) { print "true"; } else { print "False"; } 41
  • 42.
    Sample Program: use strict;re1.pl use warnings; my $str="I am student of Aditya Engineering College"; print "Before Changing:$strn"; # Matching of Pattern if($str=~s/<Engineering>/<Engg>/) { print "After changing:$strn"; } #Not Matching to a Pattern if($str=!~/python/) { print "not Matchedn"; } 42
  • 43.
    Sample Program: trans.pl $str="Iam student of Aditya Engineering College"; print "Before Changing:$strn"; if($str=~tr/Engineering/ENGINEERING/) { print "After Changing:$strn"; } 43
  • 44.
    s Matches whitespaces{n,t,r}. S Matches non whitespaces. d Matches numbers. D Matches non- numbers. (.*) To retrieve the expressions matched inside the parenthesis ^ Matches beginning of the line followed. $ Matches end of the line . Matches single character except newline To match a new line use m// [..] Any character inside square brackets. [^..] Matches characters excluding inside the square brackets. * Matches 0 or more preceding expressions. + Matches 1 or more preceding expressions ? Matches 0 or 1 receding expressions. 44
  • 45.
    {n} Matches noccurrences of preceding expressions. {n,} Matches n or more occurrences of preceding expressions. {n, m} Matches n to m occurrences of preceding expressions. n | m Matches n or m. w Matches alphabetical characters. W Matches non-alphabetical characters. 45
  • 46.
    Complex Regular Expression: SampleProgram: re.pl =head com.W.tutorialspoint.C# 5.812345 AAA // * com.X.tutorialspoint.C++ 6.815345 BBB // = =cut open(FHR,"test1.txt") or die "Cannot open file $!"; while(<FHR>) { if($_=~m{^com...w{14}.C(.*)[5-6].81[2 5]d{3}s+(AAA|BBB)(.*)[* =]$}) { print "$_n"; } } close(FHR); 46
  • 47.
    Subroutines: Calling a subroutine: Subroutine(arguments) &subroutines(arguments) // previous versions Passing arguments to subroutines: Shift $_[0],$_[1],.. @_ 47
  • 48.
    Returning values fromsubroutine: “return” keyword is used to return values followed by a scalar or a list. 48
  • 49.
    Sample Program: subroutineex.pl Usestrict; use warnings; my @lines=("google.com 100","yahoo.com 101","microsoft.com 102","gitam.org 300","au.org 301","flikart.com 302"); sub displaycomlines{ foreach(@lines){ if($_=~/com/g){ print("$_n"); } } } displaycomlines(); 49
  • 50.
    Sample Program withSingle Parameter: Use strict; use warnings; my @lines=("google.com 100","yahoo.com 101","microsoft.com 102","gitam.org 300","au.org 301","flikart.com 302"); My $msg=“org”; sub displaycomlines{ foreach(@lines){ $msg=shift; if($_=~/ $msg /){ print("$_n"); } } } displaycomlines($msg); 50
  • 51.
    Using SHIFT: (DoubleParameter) use strict; use warnings; my @lines=("google.com 100","yahoo.com 101","microsoft.com 102","gitam.org 300","au.org 301","flikart.com 302"); sub displaycomlines{ my $msg= shift; my $code=shift; foreach(@lines){ if($_=~/$msg.*$code/){ print "$_n"; } } } displaycomlines ("com", 101); 51
  • 52.
    Using Default Variable:(Double Parameter) subroutine4.pl use strict; use warnings; my @lines=("google.com 100","yahoo.com 101","microsoft.com 102","gitam.org 300","au.org 301","flikart.com 302"); sub displaycomlines{ my $msg=$_[0]; my $code=$_[1]; foreach(@lines){ if($_=~/$msg.*$code/){ print "$_n"; } } } displaycomlines ("com", 101); 52
  • 53.
    Sample Program using@_ subroutine5.pl use strict; use warnings; my @lines=("google.com 100","yahoo.com 101","microsoft.com 102","gitam.org 300","au.org 301","flikart.com 302"); sub displaycomlines{ my ($msg, $code)=@_; foreach(@lines){ if($_=~/$msg.*$code/){ print "$_n"; } } } displaycomlines("com",101); 53
  • 54.
    Sample program howto pass an array to subroutine subroutine6.pl use strict; use warnings; my @lines=("google.com 100","yahoo.com 101","microsoft.com 102","gitam.org 300","au.org 301","flikart.com 302"); sub appenddomain{ @lines=@_; foreach(@lines) { if($_=~/com/){ $_.=": COM"; } else{ $_.=": ORG"; } }; return(@lines); } @lines=appenddomain(@lines); print "@linesn“; 54
  • 55.
    Sample program howto pass an hash to subroutine subroutine7.pl use strict; use warnings; my %url=("google.com"=> 100,"yahoo.com"=> 101,"microsoft.com"=> 102,"gitam.org"=> 300,"au.org"=> 301,"flikart.com"=> 302); sub appenddomain{ %url=@_; foreach(%url) { if($_=~/com/){ $url{$_}--; } else{ $url{$_}-- ; } }; return(%url); } %url=appenddomain(%url); print %url,”n”; 55
  • 56.
    Sample Program topass multiple data types to a subroutine subroutine8.pl use strict; use warnings; my @lines=("google.com 100","yahoo.com 101","microsoft.com 102","gitam.org 300","au.org 301","flikart.com 302"); my %skillsandexperiences=(perl=>5,python=>2,unix=>5,java=>1); my @skills=("perl","python","unix","java"); sub displaylines{ (@lines, %skillsandexperiences, @skills)=@_; print "@linesn"; print %skillsandexperiences,"n"; print "@skillsn"; } displaylines(@lines,%skillsandexperiences,@skills); 56
  • 57.
    Strings: String Operations: Finding theLength of string. Changing the case. Concatenation (.). Substring Extraction. 57
  • 58.
    Sample Program: use strict; usewarnings; print "Enter first string:"; my $v1=< >; print "Enter another string:"; my $v2=< >; print "Upper case is:U$v1n"; print "Lower Case is:L$v1n"; my $v3= $v1.$v2; print "Concatenated string:",$v3,"n"; print "Length of concatenated string:",length($v3),"n"; print "Substring Extraction:",substr($v3,6,17); print "Substring Extraction From Last:",substr($v3,-5,6); 58