Perl, a cross-platform, open-source computer programming language used widely in the commercial and private computing sectors. Perl is a favourite among Web developers for its flexible, continually evolving text-processing and problem-solving capabilities.
2. 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”.
3. 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
4. Contents:
Basic i/o statements
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 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
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 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
9. 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
10. 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
11. 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
12. 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
13. 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
14. 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
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 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
17. 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
18. 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
19. 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
20. 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
21. 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
22. 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
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:
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
25. 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
26. 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
27. 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
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 there are 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;
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
37. 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
38. 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
39. 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
40. 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
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
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 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
48. Returning values from subroutine:
“return” keyword is used to return values followed by a scalar
or a list.
48
49. 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
50. 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
51. 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
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 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
55. 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
56. 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
58. 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