Download - 2. Intro to Perl
-
8/8/2019 2. Intro to Perl
1/59
Intro to Perl 1-1
Session No.2
Introduction to Perl
Deepak Chopade
-
8/8/2019 2. Intro to Perl
2/59
Intro to Perl 1-2
Course Objectives
To introduce Perl Scripting Language
To introduce the concept of regular expressions andpattern matching
To introduce various file operations in Perl To introduce the Database programming using Perl
To introduce the basics of Web Programming usingPerl
-
8/8/2019 2. Intro to Perl
3/59
Intro to Perl 1-3
What is PERL and where PERL is beingused?
PERL is scripting language
PERL is mostly used for extracting information from text files andgenerating various reports based on that
PERL is also used for developing web applications using CGI standards
It is also used for developing scripts of automated testing, systemadministration etc.
It is one of the most popular scripting language
Many projects in Infy uses Perl Scripting
-
8/8/2019 2. Intro to Perl
4/59
Intro to Perl 1-4
Course Pre-Requisites
The participants should have the basic knowledge ofprogramming
The participants should have knowledge of SQL
-
8/8/2019 2. Intro to Perl
5/59
Intro to Perl 1-5
Expectations
At the end of this course, the participants areexpected to be proficient in the following
Writing scripts using Perl
Writing simple Database related utilities in Perl
-
8/8/2019 2. Intro to Perl
6/59
Intro to Perl 1-6
Day 1 Introduction to Perl Scalar Variables I/O Functions Operators String and formatting strings Selectional, iterational and miscellaneous control statements
Arrays and various operations on arrays
Day 2 Hashes and various operations on hashes Regular Expressions Meta characters Character classes
Pattern matching Subroutines Command line arguments
Day Wise Session Plan (1/2)
-
8/8/2019 2. Intro to Perl
7/59
Intro to Perl 1-7
Day 3 File Input/Output
Various file opening modes
Database Programming using DBI & DBD
Introduction to CGI Programming using Perl
Day Wise Session Plan (2/2)
-
8/8/2019 2. Intro to Perl
8/59
-
8/8/2019 2. Intro to Perl
9/59
Intro to Perl 1-9
Session Plan Day 1
Introduction to Perl
Scalar Variables
I/O Functions
Operators
String and formatting strings
Selectional, iterational and miscellaneous control
statements
Arrays and various operations on arrays
-
8/8/2019 2. Intro to Perl
10/59
Intro to Perl 1-10
Perl Scripting
-
8/8/2019 2. Intro to Perl
11/59
Intro to Perl 1-11
PERL Practical Extraction and Report Language Developed by Larry Wall in 1987
Originally designed for reading text files and preparing reports based on that
information
Combines features of C ,sed, awk and sh Gives unlimited data size
Recursion of unlimited depth
Sophisticated pattern matching techniques
Used for web programming
Widely used for system administration
Wide range of third party modules
PERL - Introduction
-
8/8/2019 2. Intro to Perl
12/59
-
8/8/2019 2. Intro to Perl
13/59
Intro to Perl 1-13
PERL - Variables
Scalar Variables Simple variables containing an element, either a number or a string
Defined by $ symbol
Array List of scalar variables Defined by @ symbol
Hashes Similar to arrays
Each item is identified by a key value Defined by % symbol
-
8/8/2019 2. Intro to Perl
14/59
Intro to Perl 1-14
PERL Scalar Variables Defined by $ Symbol
Stores either a number or a String No declaration required, creation is done when a variable is referred first in the
program,known as auto vivification
Strings and Numbers are interchangeable
Variable names are case sensitive
Variable name can have alphabets, numbers and underscore (_)
Should not start with a number Variables starting with _ is special
$Number = 48091 #Integer type
$Name = John David #String type
$Salary = 48091.50 #Decimal type
$Message = Do you like \PERL\ Script? #String type
$Number=4809 is valid
-
8/8/2019 2. Intro to Perl
15/59
Intro to Perl 1-15
PERL First Perl Script
#File Name : Address.pl#Description : Script to display the address
#Author : Ajeesh G.P.
#Date : 12-Feb-2007
#Version : 1.0
# Information about Perl interpreter
# !c:\per\bin\perl
#Statements to display the Address
print John Dave\n;
print 937/s Hebbal II Stage\n;
print Mysore 18\t;
print Mobile: 9886045606\n;
#End of Address.pl
-
8/8/2019 2. Intro to Perl
16/59
Intro to Perl 1-16
PERL - Lists
Collection of scalar data, Arrays and Hashes Represents a logical group of items Scalar data inside ( and ) separated using , represents a list A set of operators works on list called as list operator
E.g. print print (1,2,3) displays 123
E.g.
4809
John
Dave
34000.50
($no, $name, $sal) = (4809, John Dave, 34000.50);
print $no;
print \n;
print $name;
print \n
print $sal
-
8/8/2019 2. Intro to Perl
17/59
Intro to Perl 1-17
#Generating a random letter using List
$RandomNumber = (51..150)[rand(100)];
print $RandomNumber
PERL Accessing List element usingIndex
John
43002
# Accessing the second element from list
$Name = (43002,John,34400.50)[1];
#Display the accessed element
print $Name
# Assigning one list to Other
($Number,$Name)=(43002,John);
($EmpNumber,$EmpName) = ($Number, $Name)
print $EmpNumber
print $EmpName
RandomNumber
between 51
and 150
John
-
8/8/2019 2. Intro to Perl
18/59
-
8/8/2019 2. Intro to Perl
19/59
Intro to Perl 1-19
PERL print
# Usage in printing a number & string
#Using temporary concatenation operator .
#Output to STDERR
What is the output of the following script?
4089
John
4089John
3400.5
%.2f3400.5
Outputs to
STDERR
$Number = 4089;
$Name = John;
print $Number;
print $Name;
print $Number.$Name;
print STDERR Warning: Unable to close print.pl;
$Sal=3400.50;
print $Sal;
print %0.2f,$Sal;
-
8/8/2019 2. Intro to Perl
20/59
Intro to Perl 1-20
$Name=John Dave;
$No=4809;
$Sal=3400.50;
printf(\nName:%s\nNo:%d\nSal:%.2f,$Name,$No,$Sal);
$Number = 43002;
$Salary = 34000.50;
printf (Salary of %d is.2f,$Number,$Salary);
PERL printf Salary of43002 is
34000.50
$Number = 43002;
$Salary = 34000.50;
$Out=sprintf (Salary of %d is %.2f,$Number,$Salary);
print $Out;
# Display the Number and Salary using printf
#Display Name and Number
#Above script can be re written using sprintf and print
Salary of 43002 is34000.50
Name :John Dave
No:4809
Sal:3400.50
-
8/8/2019 2. Intro to Perl
21/59
Intro to Perl 1-21
PERL warn
What happens if warn.pl is executed in the below form? perl warn.pl > output.txt
#Filename : warn.pl
# Declare & initialize variables
$ EmpSal=34500.50;
$ EmpName=John Dave;
if($EmpSal != 0) {
#Outputs to standard output stream
printf(%d %s,$EmpSal,$EmpName);
}else {
#Outputs to Standard Error Stream
warn Salary not calculated;
warn Write to file failed;
}
34500.50 JohnDave
-
8/8/2019 2. Intro to Perl
22/59
Intro to Perl 1-22
PERL - Operators
Assignment Operator
Auto increment and decrement operators
Additive operators
Multiplicative operators Exponentiation Operator
Relational Operators
Logical Operators
Range Operator Binding Operator
Arrow operator
File I/O Operator
-
8/8/2019 2. Intro to Perl
23/59
Intro to Perl 1-23
PERL Operators contd Assignment Operator (=)
Simple assignment
Compound assignment
Auto increment and decrement operator (++, --)
Additive Operator (+, -, .) Addition & Subtraction operator
Concatenation Operator (.)
6
6
Shivkumar
$Number1 = 5;
$Number2=$Number1;
$Number3=$Number2=$Number1;
$Number=5;
print ++$Number;
print $Number++;
$FirstName=Shiv; $LastName = Kumar;
$Name = $FirstName.$LastName;
print $Name;
$Result = $No1 + $No2 -20;
-
8/8/2019 2. Intro to Perl
24/59
Intro to Perl 1-24
PERL Operators contd.
Multiplicative Operators Multiplication & Division
- Repetition Operator (x)
- Exponential Operator
%of
marks =
60
64
$x=4;
$y=3;
print $x ** $y;
print Hello PERL x 10;
$Mark = 30;
$Percentage=30/50*100;
print % of marks=$Percentage;
Hello PERL will be
printed 10 times
-
8/8/2019 2. Intro to Perl
25/59
Intro to Perl 1-25
PERL operators contd
Relational Operators Operating on Numeric data=, ==, !=,
- Operating on String data
lt less than E.g. ($Myname lt $YourName)
gt greater thanle less than or equal toge greater than or equal toeq equal tone not equal tocmp compare (returns -1, 0 , 1)
- Logical Operator
AND - && or andOR - || or orNOT - not
-
8/8/2019 2. Intro to Perl
26/59
-
8/8/2019 2. Intro to Perl
27/59
Intro to Perl 1-27
PERL Standard Input
Input operator or
Read input from the user including \n from the user
chomp operator can be used for removing the \n character
By default input is stored in a default variable $_
#Read the Employee Number from the user
print Enter the Number : ;
$EmpNumber = ;
print \nEnter the Name: ;
$EmpName = ;
print \nNo : $EmpNumber \nName:$EmpName;
-
8/8/2019 2. Intro to Perl
28/59
Intro to Perl 1-28
PERL Standard Input contd
chomp Usually used to discard the \n character at the end of input string
20
Ajeesh
$No=;
$Name=;
print $No;
print $Name;
chomp $No;
chomp $Name;print $No;
print $Name;
20Ajeesh
-
8/8/2019 2. Intro to Perl
29/59
Intro to Perl 1-29
PERL - Strings
Sequence of characters, each character is an 8 bit value
Single quoted string
Escape sequence except \\ & \ are not interpreted so
Double quoted string
All escape sequences are interpreted so
No 37\nII Cross
Sheshan's
No 37
II Cross
$HouseNo = No 37\nII Cross;
$Street = Sheshan\s;
print $HouseNo;
print \n;
print $Street;
$HouseNo = "No 37\nII Cross";$Street = "Sheshans\'";
print $HouseNo;
print "\n";
print $Street;
Sheshans
-
8/8/2019 2. Intro to Perl
30/59
-
8/8/2019 2. Intro to Perl
31/59
Intro to Perl 1-31
PERL String Functions
Converting to lower case using lc STRING
Converting to upper case using uc STRING
Converting initial case to lower using lcfirst STRING
Converting initial case to upper using ucfirst STRING
notepad.exe
NOTEPAD.EXE
notePad.EXE
NotePad.EXE
$FileName= "NotePad.EXE";
$FileName=lc $FileName;
print $FileName;
$FileName= "NotePad.EXE";
$FileName=uc $FileName;
print $FileName;
$FileName= "NotePad.EXE";
$FileName=lcfirst $FileName;
print $FileName;
$FileName= "NotePad.EXE";
$FileName=ucfirst $FileName;
print $FileName;
-
8/8/2019 2. Intro to Perl
32/59
Intro to Perl 1-32
PERL String Functions contd
Getting string length using length (STRING) Returns the length of the string
If STRING is omitted, it returns the length of the string stored in $_
Searching string using index (STRING,
SUBSTRING, [POSITION]) returns the index of the first occurrence of the SUBSTRING in STRING on orafter POSITION
If POSITION is ignored, it starts searching from the first location
returns -1 if not found
rindexcan be used to find the index of the last occurrence of the SUBSTRING inSTRING on or before POSITION
9
$FileNameDOS="MyApp.Exe";
$Length=length ($FileNameDOS);
print $Length;
-
8/8/2019 2. Intro to Perl
33/59
Intro to Perl 1-33
PERL String Functions contd
Using index
Using rindex
4
15
15
4
$Domain="www.ad.infosys.ad.com";
$Result=index($Domain,"ad");
print $Result;
print "\n";
$Result=index($Domain,"ad",13);
print $Result;
$Domain="www.ad.infosys.ad.com";
$Result=rindex($Domain,"ad");
print $Result;
print "\n";
$Result=rindex($Domain,"ad",13);
print $Result;
-
8/8/2019 2. Intro to Perl
34/59
Intro to Perl 1-34
PERL String Functions contd
Extracting/Replacing substring using
substr STRING,OFFSET,[LENGTH],REPLACEMENT
Extracts and returns the substring from OFFSET to LENGTH+OFFSET
If LENGTH is omitted, extraction starts from OFFSET to end of STRING
If LENGTH is negative, extraction omits that much number of characters from theend
If OFFSET is negative extraction starts from end of the string and moves backwards
If REPLACEMENT is specified, extracted substring will be replaced byREPLACEMENT
-
8/8/2019 2. Intro to Perl
35/59
Intro to Perl 1-35
PERL String Function contd
Extracting substring:
Extracting and replacing:
Reversing the String:
http
$Source="http://www.infosys.com:8080/index.html";
$Protocol=substr($Source,0,4);
print $Protocol;
$Source="http://www.infosys.com";
substr($Source,0,4,"https");
print $Source;
$Source="www.infosys.com";
$Image= reverse($Source);
print $Image;
moc.sysofni.www
https://www.infosys.com
-
8/8/2019 2. Intro to Perl
36/59
Intro to Perl 1-36
PERL Control Structures
Branching Statements if
if else
if elsif
Looping Statements while / until do while/ until
for
foreach
Miscellaneous Control Statements last, next, redo Expression modifiers
exit, die
-
8/8/2019 2. Intro to Perl
37/59
Intro to Perl 1-37
PERL Control Structures contd if statement
if ( condition ) {#True Block
} If - else statement
if( condition ) {#True Block
}else {#False Block
} if elsif statement
If( condition1) {
#T
rue block for Condition1}elsif(condition2) {#True block for Condition2
}else {#False block
}
-
8/8/2019 2. Intro to Perl
38/59
Intro to Perl 1-38
PERL Control Structures contd
$FileSize=;
if($FileSize==-1) {
print "File Not Found!\n";
}elsif($FileSize==0) {
print "File Empty!\n";
}else {
print "Size of the file is
$FileSize";}
-
8/8/2019 2. Intro to Perl
39/59
Intro to Perl 1-39
PERL Control Structures contd
while loopwhile (condition) {
#while block statements
}
Control comes out of the loop when the condition isFALSE
until loop
until (condition) {#until block statements
}
Control comes out of the loop when the condition is TRUE
-
8/8/2019 2. Intro to Perl
40/59
Intro to Perl 1-40
PERL Control Structures contd
What is the output of the following code?
What is the output of the following code?
Prints 10 9 8 7 6
Prints 210
$Loop=10;
until($Loop
-
8/8/2019 2. Intro to Perl
41/59
Intro to Perl 1-41
PERL Control Structures contd
do while loopdo{
#while block statements
}while (condition)
Control comes out of the loop when the condition isFALSE
do until loop
do { #until block statements
}until (condition)
Control comes out of the loop when the condition is TRUE
-
8/8/2019 2. Intro to Perl
42/59
Intro to Perl 1-42
PERL Control Structures contd
What is the output of the above code if the input isJoe
What is the output of the above code if the inputs
is Exit
Prints Hello Joe
Prints Hello Exit
do {
$Text=;
chomp $Text;
if($Text ne "Exit") {
print "\nHello ".$Text;
}}until($Text eq "Exit");
-
8/8/2019 2. Intro to Perl
43/59
-
8/8/2019 2. Intro to Perl
44/59
-
8/8/2019 2. Intro to Perl
45/59
Intro to Perl 1-45
PERL Control Structures contd#Purchase a max of 12 coupons
#for7 Days Or 6 Coupons for 3#Days
$Day=1;
$TotalCoupons=0;
while($Day12) {
$Day=1;
$TotalCoupons=0;
redo; #Restart the loop}
if ((($TotalCoupons+$Coupon)>6)&& Day
-
8/8/2019 2. Intro to Perl
46/59
Intro to Perl 1-46
PERL Control Structures contd
Expression Modifiers if modifier can be tagged to an expression. Expression is evaluated only if the
condition is true
expression if (condition);
print "Enter the Salary: ";
$Salary = ;
$Incentive = $Salary*.20 if($Salary>0);
print "Incentive : $Incentive" if($Incentive>0);
-
8/8/2019 2. Intro to Perl
47/59
Intro to Perl 1-47
PERL Control Structures
exit used to terminate the execution of a script
exit 0 denotes success and exit 1 denotes failure
cannot display error messages while exiting
$Choice=
if ($Choice==4) { exit 0};
die displays the error message to STDERR stream
and terminates the execution of a script
copy($TargetFile,$SourceFile) or die File cannot be copied
-
8/8/2019 2. Intro to Perl
48/59
Intro to Perl 1-48
PERL - Arrays
Set of scalar values Dynamically grows/shrinks when ever required Prefixed with @ symbol Can store dissimilar data types Un initialized locations and locations beyond the end of array will be
undef Index starts from 0 Last index is denoted by $# Can be initialized using
List qw operator
Repetition operator (X) Range operator (..) Individual locations
-
8/8/2019 2. Intro to Perl
49/59
Intro to Perl 1-49
PERL Arrays contd
Creation
Or
Or
Or
@EmpName = (John,Dave,Mary,Jim);
@EmpNumber = (1001,1005,1008,1009);
@EmpName = qw (John Dave Mary Jim)
$EmpName[0] = John;
$EmpName[1] = Dave;
$EmpName[2] = Mary;
$EmpName[3] = Jim;
for($Loop=0;$Loop
-
8/8/2019 2. Intro to Perl
50/59
Intro to Perl 1-50
PERL Arrays contd
Creation using Range operator@EmpNumber = (1001..1200) ;
- Can be used if array has to be initialized by a range of elements
Creation using Repetition operator@Number = (0) X 10;- Can be used if array has to be initialized by same value in all locations
Creation of array with dissimilar elements@Details=(1001,John,3400.50);
-
8/8/2019 2. Intro to Perl
51/59
Intro to Perl 1-51
PERL Arrays contd
Displaying the array elements@Number=(101,102,103,104); To print the whole array
To print the individual elements
- To print the elements using a loop
101102103104
101,102,103,104
print @Number;
print join(,,@Number);
print $Number[0];
print $Number[1];
print $Number[2];
print $Number[3];
@Emp=(1..5);foreach $i (0..4) {
print $Emp[$i];
print " ";
}
1 2 3 4 5
101102103104
-
8/8/2019 2. Intro to Perl
52/59
Intro to Perl 1-52
PERL Arrays contd
Length of the array $# stores the last index of the array
$# +1 will give the number of elements
Emptying an array
$#Emp = -1;
OR@Emp = ( );
OR
@Emp = undef;
3
@Emp=(1001,1002,1003);
$NoElements=$#Emp+1;
print "No of elements=$NoElements";
-
8/8/2019 2. Intro to Perl
53/59
Intro to Perl 1-53
PERL Arrays contd
Pushing and Popping elements push (, /)
Will add the element to the end of array
Array expands automatically pop ()
Will remove the element from the end of the array
Array shrinks automatically
101,102
101,102,103
103
@Emp=(101,102);
print join(',',@Emp);
push (@Emp,103);
print join(',',@Emp);
$No=pop(@Emp);
print \n.$No;
print join(',',@Emp);
101,102
-
8/8/2019 2. Intro to Perl
54/59
Intro to Perl 1-54
PERL Arrays contd
Shifting and Unshifting unshift (, /) Will add the element/list to the front of the array & returns number
of elements
Array expands automatically shift ()
Will remove the element from front of the array Array shrinks automatically
101,102
100,101,102
100
101,102
@Emp=(101,102);
print join(',',@Emp);
unshift (@Emp,100);
print join(',',@Emp);
$No=shift(@Emp);
print $No;
print join(',',@Emp);
-
8/8/2019 2. Intro to Perl
55/59
Intro to Perl 1-55
PERL Arrays contd
Merging of arrays using push
Array Slices (Section of an array)
10,11,12,105,106,107
101,102,103,104
,1150,1151,1152
101,102,103,104
1150,1151,1152
@Emp=(101,102,103,104,1150,1151,1152);
print join(',',@Emp);
@Senior=@Emp[0..3];
print join(',',@Senior);
@Junior=@Emp[4..6];
print join(',',@Junior);
@EmpOld=(10,11,12);
@EmpNew=(105,106,107);
push (@Emp,@EmpOld);
push (@Emp,@EmpNew);
print join(',',@Emp);
-
8/8/2019 2. Intro to Perl
56/59
Intro to Perl 1-56
PERL Arrays Contd
Reversing an Array using reverse@
Sorting an Array using sort @
Dave, Jim, John, Mary
104,103,102,101
@Name=("Jim","John","Dave","Mary");
@Name=sort @Name;
print join(',',@Name);
@List=(101,102,103,104);
@rList=reverse (@List);
print join(',',@rList);
-
8/8/2019 2. Intro to Perl
57/59
-
8/8/2019 2. Intro to Perl
58/59
Intro to Perl 1-58
Summary
Scalar Variables
Perl List
Display Functions
Operators Standard input using /
Strings and various string functions
Conditional constructs
Looping constructsMiscellaneous control statements
Arrays
-
8/8/2019 2. Intro to Perl
59/59
Thats all for today!
Any questions?
Thank you!