0% found this document useful (0 votes)
42 views

Intro To Perl

The document provides an introduction and session plan for a Perl scripting language course, outlining objectives to introduce Perl concepts like regular expressions, file operations, and database and web programming using Perl over 3 days of sessions covering Perl basics, arrays, hashes, regular expressions, and more.

Uploaded by

Navneet Rai
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
42 views

Intro To Perl

The document provides an introduction and session plan for a Perl scripting language course, outlining objectives to introduce Perl concepts like regular expressions, file operations, and database and web programming using Perl over 3 days of sessions covering Perl basics, arrays, hashes, regular expressions, and more.

Uploaded by

Navneet Rai
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 59

Session No.

Introduction to Perl

Deepak
Chopade

Intro to Perl 1-1


Course Objectives

To introduce Perl Scripting Language


To introduce the concept of regular expressions
and pattern matching
To introduce various file operations in Perl
To introduce the Database programming using Perl
To introduce the basics of Web Programming using
Perl

Intro to Perl 1-2


What is PERL and where PERL is being
used?
PERL is scripting language
PERL is mostly used for extracting information from text files and
generating 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, system
administration etc.
It is one of the most popular scripting language
Many projects in Infy uses Perl Scripting

Intro to Perl 1-3


Course Pre-Requisites

The participants should have the basic knowledge of


programming
The participants should have knowledge of SQL

Intro to Perl 1-4


Expectations

At the end of this course, the participants are


expected to be proficient in the following
 Writing scripts using Perl
 Writing simple Database related utilities in Perl

Intro to Perl 1-5


Day Wise Session Plan (1/2)

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

Intro to Perl 1-6


Day Wise Session Plan (2/2)

Day 3
 File Input/Output
 Various file opening modes
 Database Programming using DBI & DBD
 Introduction to CGI Programming using Perl

Intro to Perl 1-7


References

 Learning Perl : Randal Schwartz, Tom Christiansen & Larry Wall,


O’reilly

 Programming Perl: Larry Wall, Tom Christiansen & Jon Orwant,


O’reilly

 Advanced Perl Programming : Sriram Srinivasan, O’reilly

 Perl Cookbook : Tom Christiansen & Nathan Torkington, O’reilly

 Perl in a Nutshell : Siever, Spainhour & Nathan Patwardhan, O’reilly

 Perl for System Administration : David N. Blank-Edelman, O’reilly

Intro to Perl 1-8


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

Intro to Perl 1-9


Perl Scripting

Intro to Perl 1-10


PERL - Introduction

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

Intro to Perl 1-11


The PERL Interpreter

Perl Interpreter
 Converts the scripts in to a parse tree and executes immediately
 Internally Perl maintains a byte code for execution
 Known as interpreter/ compiler

Intro to Perl 1-12


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

Intro to Perl 1-13


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

Intro to Perl 1-14


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

Intro to Perl 1-15


PERL - Lists
 Collection of scalar data, Arrays and Hashes
 Represents a logical group of items 4809
 Scalar data inside ( and ) separated using , represents a list
 A set of operators works on list – called as list operator
• E.g. print John
• print (1,2,3) displays 123 Dave

E.g. 34000.50

($no, $name, $sal) = (4809, “John Dave”, 34000.50);


print $no;
print “\n”;
print $name;
print “\n”
print $sal

Intro to Perl 1-16


PERL – Accessing List element using John
Index
# Accessing the second element from list Random
$Name = (43002,”John”,34400.50)[1]; Number
#Display the accessed element between 51
print $Name and 150

#Generating a random letter using List


43002
$RandomNumber = (51..150)[rand(100)];
print $RandomNumber
John
# Assigning one list to Other
($Number,$Name)=(43002,”John”);
($EmpNumber,$EmpName) = ($Number, $Name)
print $EmpNumber
print $EmpName
Intro to Perl 1-17
PERL – Display Functions
print
 Unformatted output statement which can print a string, Number or a List
 Default outputs to STDOUT, can be redirected to STDERR or a File
 Returns ‘true’ if successful else ‘false’ [1 represents ‘true’]
print List
print FILEHANDLE List
printf
 Formatted output statement
 By defaults outputs to STDOUT. Can be redirected to STDERR or a File
printf Format, List
printf FILEHANDLE, Format, List

warn
 Outputs a message on the STDERR stream (unbuffered)
 Used to trace error when STDOUT is redirected
 Program is neither terminated nor an exception is thrown
warn “Message”

Intro to Perl 1-18


4089
PERL – print
# Usage in printing a number & string
John
$Number = 4089;
$Name = “John”;
print $Number;
4089John
print $Name;
#Using temporary concatenation operator ‘.’
print $Number.$Name; Outputs to
STDERR
#Output to STDERR
print STDERR ”Warning: Unable to close print.pl”; 3400.5
What is the output of the following script?
$Sal=3400.50; %.2f3400.5
print $Sal;
print “%0.2f”,$Sal;

Intro to Perl 1-19


PERL – printf Salary of
43002 is
# Display the Number and Salary using printf 34000.50
$Number = 43002; Name :John Dave
$Salary = 34000.50; No:4809
printf (“Salary of %d is.2f”,$Number,$Salary);Sal:3400.50

#Display Name and Number


Salary of 43002 is
$Name=“John Dave”; 34000.50
$No=4809;
$Sal=3400.50;
printf(“\nName:%s\nNo:%d\nSal:%.2f”,$Name,$No,$Sal);

#Above script can be re written using sprintf and print


$Number = 43002;
$Salary = 34000.50;
$Out=sprintf (“Salary of %d is %.2f”,$Number,$Salary);
print $Out;
Intro to Perl 1-20
PERL – warn
#Filename : warn.pl
# Declare & initialize variables 34500.50 John
Dave
$ 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”;
}

What happens if warn.pl is executed in the below form?


<Unix-Prompt$> perl warn.pl > output.txt

Intro to Perl 1-21


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

Intro to Perl 1-22


PERL – Operators contd
 Assignment Operator (=)
6
 Simple assignment

$Number1 = 5;
 Compound assignment
$Number2=$Number1; 6
 Auto increment and decrement operator (++, --)
$Number3=$Number2=$Number1;
Shivkumar
$Number=5;
 Additive Operator (+, -, .)

print ++$Number;
Addition & Subtraction operator
print $Number++;
 Concatenation Operator (.)

$Result = $No1 + $No2 -20;

$FirstName=“Shiv”; $LastName = “Kumar”;


$Name = $FirstName.$LastName;
print $Name;
Intro to Perl 1-23
PERL – Operators contd. %of
marks =
60
Multiplicative Operators
 $Mark
Multiplication = 30;
& Division Hello PERL will be
printed 10 times
$Percentage=30/50*100;
print “% of marks=$Percentage”;
64
- Repetition Operator (x)

print “Hello PERL” x 10;


- Exponential Operator

$x=4;
$y=3;
print $x ** $y;

Intro to Perl 1-24


PERL – operators contd
Relational Operators
 Operating on Numeric data
<, <=, >, >=, ==, !=, <=>

- Operating on String data


lt – less than E.g. ($Myname lt $YourName)
gt – greater than
le – less than or equal to
ge – greater than or equal to
eq – equal to
ne – not equal to
cmp – compare (returns -1, 0 , 1)

- Logical Operator
AND - && or ‘and’
OR - || or ‘or’
NOT - not
Intro to Perl 1-25
PERL – Operators contd
Range Operator (..)
• Returns a list of sequence of values
print (1..50);
print (a..z);
Bind Operator (=~, !~)
• Used for binding scalar expressions to a pattern match
Arrow Operator (->)
• Used to retrieve elements from a reference
File Operator (<File_Handle>)
• Used for File I/O Operations
• <> represents <STDIN>

Note: Bind, Arrow and File operators will be explained later


Intro to Perl 1-26
PERL – Standard Input

Input operator
 <STDIN> 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 = <STDIN>;
print “\nEnter the Name: “;
$EmpName = <STDIN>;
print “\nNo : $EmpNumber \nName:$EmpName”;

Intro to Perl 1-27


PERL – Standard Input contd 20
Ajeesh
chomp
 Usually used to discard the ‘\n’ character at the end of input string

$No=<STDIN>;
$Name=<STDIN>;
20Ajeesh
print $No;
print $Name;
chomp $No;
chomp $Name;
print $No;
print $Name;

Intro to Perl 1-28


PERL - Strings
No 37\nII Cross

 Sequence of characters, each character is an 8 bit value


 Single quoted string Sheshan's
• Escape $HouseNo
sequence except
= ‘No\\37\nII
& \’ are Cross’;
not interpreted so
$Street = ‘Sheshan\’s’;
print $HouseNo;
print “\n”;
print $Street; No 37
II Cross
 Double quoted string
$HouseNo = "No 37\nII Cross"; Sheshans’
• All escape sequences
$Street are interpreted so
= "Sheshans\'";
print $HouseNo;
print "\n";
print $Street;

Intro to Perl 1-29


PERL – String Operators
/etc/bin/MyApplication.exe
Concatenation Operator
 ‘.’ can be used for concatenating string values
$Name="MyApplication";
$Extention=".exe"; 555

$Dir="/etc/bin";
$FileName=$Dir."/".$Name.$Extention;
print $FileName;

Repetition Operator
$RandFancyNum="5" x 3;
 ‘x’ makes as many number of concatenated copies of string
print $RandFancyNum;

Intro to Perl 1-30


PERL – String Functions
Converting to lower case using – lc STRING notepad.exe
$FileName= "NotePad.EXE";
$FileName=lc $FileName;
print $FileName; NOTEPAD.EXE

Converting to upper case


$FileName= using – uc
"NotePad.EXE"; STRING
$FileName=uc $FileName; notePad.EXE
print $FileName;

NotePad.EXE
$FileName= "NotePad.EXE";
Converting initial case to lower
$FileName=lcfirst using
$FileName; – lcfirst STRING
print $FileName;

$FileName= "NotePad.EXE";
$FileName=ucfirst $FileName;
Converting initial case to upper using – ucfirst STRING
print $FileName;
Intro to Perl 1-31
PERL – String Functions contd
9
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 $_
$FileNameDOS="MyApp.Exe";
$Length=length ($FileNameDOS);
print $Length;

index (STRING,
Searching string using –
SUBSTRING, [POSITION])
 returns the index of the first occurrence of the SUBSTRING in STRING on or after
POSITION
 If POSITION is ignored, it starts searching from the first location
 returns -1 if not found
 rindex can be used to find the index of the last occurrence of the SUBSTRING in
STRING on or before POSITION

Intro to Perl 1-32


PERL – String Functions contd 4

Using$Domain="www.ad.infosys.ad.com";
index 15
$Result=index($Domain,"ad");
print $Result;
print "\n";
$Result=index($Domain,"ad",13); 15
print $Result;

4
$Domain="www.ad.infosys.ad.com";

Using$Result=rindex($Domain,"ad");
rindex
print $Result;
print "\n";
$Result=rindex($Domain,"ad",13);
print $Result;

Intro to Perl 1-33


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 the
end
 If OFFSET is negative extraction starts from end of the string and moves back
wards
 If REPLACEMENT is specified, extracted substring will be replaced by
REPLACEMENT

Intro to Perl 1-34


PERL – String Function contd http

Extracting substring:
$Source="http://www.infosys.com:8080/index.html";
$Protocol=substr($Source,0,4);
print $Protocol;

Extracting and replacing:


$Source="http://www.infosys.com";
substr($Source,0,4,"https"); https://www.infosys.com
print $Source;

$Source="www.infosys.com";
Reversing the String:
$Image= reverse($Source); moc.sysofni.www

print $Image;

Intro to Perl 1-35


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

Intro to Perl 1-36


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) {
#True block for Condition1
}elsif(condition2) {
#True block for Condition2
}else {
#False block
}

Intro to Perl 1-37


PERL – Control Structures contd

$FileSize=<STDIN>;
if($FileSize==-1) {
print "File Not Found!\n";
}elsif($FileSize==0) {
print "File Empty!\n";
}else {
print "Size of the file is
$FileSize";
}

Intro to Perl 1-38


PERL – Control Structures contd

while loop
while (condition) {
#while block statements
}
Control comes out of the loop when the condition is FALSE

until loop
until (condition) {
#until block statements
}
Control comes out of the loop when the condition is TRUE

Intro to Perl 1-39


PERL – Control Structures contd

What is the output of the following code?


$Loop=10;
until($Loop<=5) {
print $Loop;
$Loop--;
}
Prints 10 9 8 7 6

What is the output of the following code?


$Loop=3;
while($Loop--) {
print $Loop;
}
Prints 210
Intro to Perl 1-40
PERL – Control Structures contd

do while loop


do{
#while block statements
}while (condition)
Control comes out of the loop when the condition is FALSE

do until loop


do {
#until block statements
}until (condition)
Control comes out of the loop when the condition is TRUE

Intro to Perl 1-41


PERL – Control Structures contd
do {
$Text=<STDIN>;
chomp $Text;
if($Text ne "Exit") {
print "\nHello ".$Text;
}
}until($Text eq "Exit");

What is the output Prints


of the above code if the input is “Joe”
Hello Joe

What is the output of the above code if the inputs is “Exit”


Prints Hello Exit

Solution?

Intro to Perl 1-42


John, Welcome to E&R
PERL – Control Structures contd Dave, Welcome to E&R

for Mary, Welcome to E&R

for(init expr ; condition ; increment/decrement ) {


#for block
}
foreach
 mostly used when iteration has to be done for different values in a list
1001 – Generated
foreach Variable (LIST) { 1002 - Generated
#Block of Statements 1003 – Generated
}
foreach $Name (“John”,”Dave”,”Mary”) { 1004 - Generated
print “$Name, Welcome to E&R\n”; 1005 - Generated
}
foreach $Number (1001..1005) {
print “$Number – Generated\n”
}

Intro to Perl 1-43


PERL – Control Structures contd
continue
 flow control statement follows while or foreach loop
 continue block will be executed after every successful completion of an iteration
next
 used to continue with the next iteration of the loop by stopping current iteration
 cannot be used in side do-while/do-until loop
 if continue block is present it will also be executed
redo
 restarts the loop without evaluating the condition again
 continue block is not executed, if present
last
 exits the loop
 continue block is not executed, if present

Intro to Perl 1-44


PERL – Control Structures contd
#Purchase a max of 12 coupons if ( ($TotalCoupons+$Coupon)>12) {
#for7 Days Or 6 Coupons for 3
#Days $Day=1;
$Day=1; $TotalCoupons=0;
$TotalCoupons=0; redo; #Restart the loop}
while($Day<8) { if ( (($TotalCoupons+$Coupon)>6)
&& Day <=3)) {
print "Enter the coupons for Day
$Day [-1 to exit]:"; $Day=1;
$Coupon=<STDIN>; $TotalCoupons=0;
chop $Coupon; redo; #Restart the loop
if ($Coupon==-1) { }
last;# Loop Termination }continue {
} $TotalCoupons =
$TotalCoupons+$Coupon;
if($Coupon=0) {
$Day++;
next;#Next iteration
}
}

Intro to Perl 1-45


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 = <STDIN>;
$Incentive = $Salary*.20 if($Salary>0);
print "Incentive : $Incentive" if($Incentive>0);

Intro to Perl 1-46


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=<STDIN>
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”

Intro to Perl 1-47


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 $#<array name>
 Can be initialized using
• List
• qw operator
• Repetition operator (X)
• Range operator (..)
• Individual locations

Intro to Perl 1-48


PERL – Arrays contd

Creation
@EmpName = (“John”,”Dave”,”Mary”,”Jim”);
@EmpNumber = (1001,1005,1008,1009);

@EmpName = qw (John Dave Mary Jim)


Or

$EmpName[0] = “John”;
Or
$EmpName[1] = “Dave”;
$EmpName[2] = “Mary”;
$EmpName[3] = “Jim”;

for($Loop=0;$Loop<5;$Loop++) {
$Number[$Loop] = <STDIN>;
Or
}
Intro to Perl 1-49
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);

Intro to Perl 1-50


PERL – Arrays contd 101102103104

Displaying the array elements


@Number=(101,102,103,104);
101,102,103,104
 To print the whole array

print @Number;
 Toprint
print thejoin(‘,’,@Number);
individual elements
101102103104

print $Number[0];
print $Number[1];
- To print
print the $Number[2];
elements using a loop 12345
print $Number[3];

@Emp=(1..5);
foreach $i (0..4) {
print $Emp[$i];
print " ";
}

Intro to Perl 1-51


PERL – Arrays contd

Length of the array


 $#<array name> stores the last index of the array 3
 $#<array name> +1 will give the number of elements
@Emp=(1001,1002,1003);
$NoElements=$#Emp+1;
print "No of elements=$NoElements";

Emptying an array

$#Emp = -1;
OR
@Emp = ( );
OR
@Emp = undef;

Intro to Perl 1-52


PERL – Arrays contd

Pushing and Popping elements 101,102


 push (<Array>, <Value>/<List>)
• Will add the element to the end of array
• Array expands automatically
 pop (<Array>)
101,102,103
• Will remove the element from the end of the array
• Array shrinks automatically
@Emp=(101,102);
print join(',',@Emp);
push (@Emp,103);
103
print join(',',@Emp);
$No=pop(@Emp);
print “\n”.$No; 101,102
print join(',',@Emp);

Intro to Perl 1-53


PERL – Arrays contd
Shifting and Unshifting
 unshift (<Array>, <Value>/<List>)
• Will add the element/list to the front of the array & returns number
of elements
• Array expands automatically 101,102
 shift (<Array>)
• Will remove the element from front of the array
• Array shrinks automatically 100,101,102
@Emp=(101,102);
print join(',',@Emp);
unshift (@Emp,100);
print join(',',@Emp);
100
$No=shift(@Emp);
print $No;
print join(',',@Emp); 101,102

Intro to Perl 1-54


PERL – Arrays contd 10,11,12,105,106,107

101,102,103,104,
Merging of arrays using push
@EmpOld=(10,11,12); 1150,1151,1152
@EmpNew=(105,106,107);
push (@Emp,@EmpOld); 101,102,103,104
push (@Emp,@EmpNew);
print join(',',@Emp);
1150,1151,1152

@Emp=(101,102,103,104,1150,1151,1152);
Array Slices (Section of an array)
print join(',',@Emp);
@Senior=@Emp[0..3];
print join(',',@Senior);
@Junior=@Emp[4..6];
print join(',',@Junior);

Intro to Perl 1-55


PERL – Arrays Contd

Reversing an Array using – reverse @<array_name>


104,103,102,101
@List=(101,102,103,104);
@rList=reverse (@List);
print join(',',@rList);

Dave, Jim, John, Mary

Sorting an Array using – sort @<array_name>


@Name=("Jim","John","Dave","Mary");
@Name=sort @Name;
print join(',',@Name);

Intro to Perl 1-56


Can you answer these questions?
• What are Scalar Variables?
• What are the display functions available in Perl?
• How to accept input from the user?
• What is the difference between for and foreach loop?
• Compare next, redo and last statement.
• What is the technique to find out the last index of an array?
• How to empty an array?

Intro to Perl 1-57


Summary

Scalar Variables
Perl List
Display Functions
Operators
Standard input using <STDIN>/<>
Strings and various string functions
Conditional constructs
Looping constructs
Miscellaneous control statements
Arrays

Intro to Perl 1-58


That’s all for today!

Any questions?

Thank you!

Intro to Perl 1-59

You might also like