The document provides an extensive introduction to Perl programming language, its features, and basic constructs such as data types, variables, control structures, and loops. It covers topics including scalar values, arrays, hashes, operators, and I/O statements with examples of usage. Practical demonstrations of Perl programming are included throughout the document to illustrate concepts.
Perl, developed in 1987 by Larry Wall, is a versatile language for text processing, automation, web applications, and database integration. Its file extension is .pl.
Perl integrates features from languages like C and supports text processing tools, databases, and a powerful regex engine. It's case sensitive and an interpreted language.
Covers programming fundamentals in Perl including I/O statements, data types, control structures, arrays, hashes, and subroutines.
Teaches input using STDIN and output using print statements, illustrated with a program calculating the area of a square.
Describes Perl’s three data types: scalars, arrays, and hashes, with examples showcasing their declaration and usage.
Explains variable declaration, arithmetic operations, concatenation, repetition using example programs for clarity.
Details characteristics of arrays, including creation, access methods, functions for modification (push, pop, splice), and string manipulation techniques.
Explains hash data structures, key-value pairs, several accessing methods, and operations like checking key existence and adding/deleting pairs.
Defines scalar variables, their characteristics, arithmetic operations, concatenations, and vstrings concept with examples.
Discusses combining scalars into expressions using various operators, providing a sample program for arithmetic operations.
Detailing numeric and string relational operators in Perl, with sample programs demonstrating usage and comparisons.
Describes various control structures including if, unless, and the ternary operator, with multiple examples illustrating their applications.
Overview of different looping constructs (while, for, foreach) in Perl, including their syntax and sample programs.
Introduces regular expressions in Perl, describing matching, substituting patterns, and complex expressions using example programs.
Explains subroutine creation, argument passing, returning values, and examples of using arrays and hashes within subroutines.
Covers string manipulations such as length, case changes, concatenation, and substring extraction with example code.
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 ANDand
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
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
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
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
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
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