Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
5 views185 pages

Unit III Perl

Uploaded by

Bindu
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views185 pages

Unit III Perl

Uploaded by

Bindu
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 185

UNIT-III

PERL Scripting
What is Perl
-Perl was originally developed by Larry Wall in 1987 as a general-
purpose Unix scripting language to make report processing easier.
- PERL stands for Practical Extraction & Report Language
- Perl is a Scripting language which can be used for a large variety of
tasks.
- A typical simple use of Perl would be for extracting information from
a text file and printing out a report or for converting a text file into
another form.
- Programs written in Perl are called Perl scripts, whereas the term the
perl program refers to the system program named perl for executing
Perl scripts.
Why Perl?
- You can avoid dealing with many problems like memory allocation and
freeing, passing a context variable to a function, or inconvenient syntax for
complex data structures.
- The code is brief and effective.
- With a small amount of awareness your code can be portable across all
UNIX operating systems, and even on Windows and other platforms.
Perl Features
• Perl takes the best features from other languages, such as C, awk,
sed, sh, and BASIC, among others.
• Perls DBI(database integration interface) supports third-party
databases including Oracle, Sybase, Postgres, MySQL and others.
• Perl works with HTML, XML, and other mark-up languages.
• Perl supports both procedural and object-oriented programming.
• Perl can be integrated with C/C++ through SWIG(Simplified
Wrapper and Interface Generator).
• The Perl interpreter can be embedded into other systems.
Perl used for
Perl has been successfully used for a lot of diverse tasks:

system administration

text processing

Database interconnectivity

web programming

GUI programming

games programming

bio-informatics

testing and quality assurance.
Real time Applications of PERL
• Amazon uses a lot of Perl to run Amazon.com
• Slashdot was built in Perl
• Movable Type blogging software is written in Perl
• Python and Perl are used to enable developers using a mobile SDK to
create mobile apps
• Perl was used to build OTRS, a ticket management system. Perl has also
been used to build a similar help desk and customer support
management system.
• Perl is used in flight simulator systems to train commercial and military
pilots
Perl Installation
Windows Installation
•Strawberry perl is open-source perl for windows which is same as others and include
CPAN modules rather than binary packages.

•DWIM perl for windows is open source perl for windows based on Strawberry perl. It
includes as much as CPAN modules as possible. It comes with Padre, the Perl IDE.
(Note: CPAN (the Comprehensive Perl Archive Network) is the central repository for
everything Perl.
It contains the collected wisdom of the entire Perl community: hundreds of Perl modules
and scripts, several books' worth of documentation, and the entire Perl distribution.)
Here are the steps to install Perl on Windows machine.
•Follow the link for the Strawberry Perl installation on Windows
http://strawberryperl.com
•Download either 32bit or 64bit version of installation.
•Run the downloaded file by double-clicking it in Windows Explorer.
This brings up the Perl install wizard, which is really easy to use. Just
accept the default settings, wait until the installation is finished, and
you're ready to roll!
Running Perl

The following are the different ways to start Perl.


•Interactive Interpreter
•You can enter perl and start coding right away in the interactive
interpreter by starting it from the command line. You can do this from
Unix, DOS, or any other system, which provides you a command-line
interpreter or shell window.
•$perl -e <perl code> # Unix/Linux
•or C:>perl -e “perl code” # Windows/DOS
Script from the Command-line

• A Perl script is a text file, which keeps perl code in it and it can be
executed at the command line by invoking the interpreter on your
application, as in the following −

• $perl script.pl # Unix/Linux or


• C:>perl script.pl # Windows/DOS
Integrated Development
Environment
• You can run Perl from a graphical user interface (GUI) environment as
well.
• All you need is a GUI application on your system that supports Perl.
• You can download Padre, the Perl IDE.
• You can also use Eclipse Plugin EPIC - Perl Editor and IDE for Eclipse if
you are familiar with Eclipse.
#include <stdio.h>
main()
{
printf("Hello World!\n");
}

and here it in Java:


public class Hello {
public static void main(String[ ] args)
{
System. out .println ("Hello World!") ;
}
}
contrast, the Perl version is a with no additional clutter:
print "Hello World!\n";
Names & values in perl
- like any other procedural language Perl manipulates variables which has a
name(or identifier) & a value.
- a notable characteristic of Perl is that variable names start with a special
character that denotes the kind of thing that the name stands for
-scalar data($)
-arrays(@)
- hash(associative array %)
-subroutine(&)
Perl Data types / Data structures
•Scalar − Scalars are simple variables & holds only one
value at a time.
-A scalar is either a number, a string, or a reference.
-A reference is actually an address of a variable
• Arrays − Arrays are ordered lists of scalars that you
access with a numeric index which starts with 0.
•Hashes − Hashes are unordered sets of key/value
pairs that you access using the keys as subscripts.
Scalar data
• In common with many scripting languages Perl recognizes just two
kinds of scalar data: strings and numbers.
• There is no distinction between integer & real numbers as different
types - a number is a number.
• Internally, numbers are stored as signed integers if possible, and
otherwise as double length floating point numbers in the systems
native format.
• Strings are stored as sequences of bytes of unlimited length .
• Perl is a dynamically typed language : the system keeps track of
whether a variable contains a numeric value or a string value
The following are examples of legal scalar
variable names:
$x
$var
$my_variable
$var2
$a_new_variable
These, however, are not legal scalar variable names:
variable # the $ character is missing
$ # there must be at least one letter in the name
$47x # second character must be a letter
$_var # again, the second character must be a letter
$variable! # you can't have a ! in a variable name
$new.var # you can't have a . in a variable name

Perl variables are case-sensitive. This means that the following variables are different:
$VAR
$var
$Var
$age = 25; # An integer
assignment
$name = "John Paul"; # A string
$salary = 1445.50; # A floating
point
print "Age = $age\n";
print "Name = $name\n";
print "Salary = $salary\n";
Scalar Operations
$str = "hello" . "world"; # Concatenates strings.
$num = 5 + 10; # adds two numbers.
$mul = 4 * 5; # multiplies two numbers.
$mix = $str . $num; # concatenates string and number.
print "str = $str\n";
print "num = $num\n";
print "mix = $mix\n";

This will produce the following result −


str = helloworld
num = 15
mix = helloworld15
Special Literals
print “hello world\n”
print "File name ". __FILE__ . "\n";
print "Line Number " . __LINE__ ."\n";
print "Package " . __PACKAGE__ ."\n";
# they can not be interpolated
print "__FILE__ __LINE__ __PACKAGE__\n";

This will produce the following result −


Hello world
File name hello.pl
Line Number 4
Package main
Variables can be declared explicitly using my statement,
e.g. my $x,my $y, my $z;

e.g. script
my $x, $y, $z;
$x=10;
$y=5;
$z=$x+$y;
print "$z\n";
print "hello world";
• We can choose to declare all variables if we wish
• We can tell Perl to insist on declarations by placing the line
use strict 'vars’
or just
use strict;
at the start of a script.

e.g. script
use strict 'vars';
my $x, my $y, my $z;
$x=10;
$y=5;
$z=$x+$y;
print "$z\n";
print "hello world";
Boolean values
•Since scalar values are either numbers or strings, some convention is
needed for representing Boolean values.
•Perl adopts the simple rule that numeric zero, "0" and the empty
string ("") mean false, and anything else means true.

Numeric constants
•Numeric constants (number literals) can be written in a variety of
ways, including scientific notation, octal and hexadecimal.
•Some possible number formats are illustrated below.
e.g. 123 , 122.45, 122.45e-5 ,4929712198024,
4929_712 198_024 ,0377 (octal) , Ox3fff (hex)
String constant
- can be enclosed in single or double quotes.
- the q (quote) & qq(double quote) operators allow you to use any
character as a quoting character.
Syntax: q /any string/ or q(any string) or q<any string> are same as 'any

string'
qq/any string/ or qq(any string) or qq<any string> is same as “any
string”
Quote-like Operators

Operator & Description


q{ } Encloses a string with-in single quotes
Example − q{abcd} gives 'abcd'
qq{ } Encloses a string with-in double quotes
Example − qq{abcd} gives "abcd“
qx{ } Encloses a string with-in invert quotes
Example − qx{abcd} gives `abcd`
qw quote word
• The qw operator in Perl is used to extract each element of the given
string as it is in an array of elements in single-quote ( ‘ ‘ ).
Syntax: qw(String)
Parameters:
String : It is the input string whose each element is extracted.
 Returns: each element of the given string as it is an array of
elements in single-quote (‘ ‘).
• This function stands for quote word because it considers each word
of the given string as it is quoted like qw(this is quote word) is
equivalent to (‘this’, ‘is’, ‘quote’,’word’).
• Here qw() uses parentheses so it seems like it is a function but it is
not. It uses different types of delimiters which are shown below:
 qw/Ram is a boy/;
 qw{Sita is a girl}
 qw[Sita is a girl];
 qw’Hello World’;
qw“Scripting Languages";
qw! Ram is a boy!;
qw@ Ram is a boy@;
Stirngs:
$a="world";
$b="hello $a";
$e="hello";
$f=$e.$a;
print "$f\n";
print "$b\n";
$c="java";
$d="$c script";
print "$d\n";
-o/p
C:\Strawberry\perl>perl c.pl
helloworld
hello world
java script
q and qq operator example:

$a=qq/world/;
$b=qq/hello $a/;
$e=q(hello);
$f=$e.$a;
print "$f\n";
print "$b\n";
$c=q(java);
$d="$c script";
print "$d\n";
Scalar expressions
-Scalar data items are combined into expressions using operators.
-Perl has a lot of operators which are ranked in 22 precedence levels
1. Arithmetic operators(+,-,*,/,%)
- Perl provides usual arithmetic operators including Exponent operator.
** (Exponent) Performs exponential (power) calculation on operators
Example −if $a=10,$b=20 then $a**$b will give 10 to the power 20

2. string operators
- String processing is done using built-in functions & regular expressions.
- perl uses a period operator for concatenation of strings
e.g. $a=”hello”; $b=”world”; $c=$a.$b;
- the other string operator is x which is used to replicate string
e.g $a=”hello”x3
Sets $a to “hellohellohello”
3. Miscellaneous Operators (..,++,- -,->)
4. Unary minus
5. Comparison operators
Integer comparision: <,>,==,>=,<=,!=,<=>
< = > :Checks if the value of two operands are equal or not, and
returns -1, 0, or 1 depending on whether the left argument is
numerically less than, equal to, or greater than the right argument.
Example − if $a=10 and $b=20 then ($a <=> $b) returns -1.

String comparision: lt, gt, eq, le, ge, ne,cmp

cmp: Returns -1, 0, or 1 depending on whether the left argument is


stringwise less than, equal to, or greater than the right argument.
Example − if $a=“abc” and $b=“xyz” then ($a cmp $b) is -1.

Perl compares strings by determining their places in an alphabetical


order.
6. Logical operators: !,&&,|| (not, and,or)
7. bitwise operators: ~,&,|,^,<<,>>
8. conditional operator: test?true expr:false expr
9. Perl Assignment Operators(=,+=,-=,*=,/=,%=,**=)
$a=10;
$b=20;
print $a;
print $b;
print "$a+$b\n";
print $a+$b;
$c=$a+$b;
print "the addition is $c";

C:\Strawberry>perl var.pl
102010+20
30
The addition is 30
Loops and Decisions

if

if else

If-elsif..else (nested if-else)

while

do-while

for

foreach

until
A program containing a simple example of an if statement.
$number = 5;
if ($number) {
print ("The number is not zero.\
n");
}
print ("This is the last line of the
program.\n");

$ program2_2
The number is not zero.
This is the last line of the program.
$
A program that uses the if-else statement.

$number1 = 5;
$number2 = 6;
if ($number1 == $number2) {
print ("The two numbers are equal.\n");
}
else {
print ("The two numbers are not equal.\n");
}
print ("This is the last line of the program.\n");
if...elsif...else
An if statement can be followed by an optional elsif...else statement, which is
very useful to test the various conditions using single if...elsif statement.
When using if , elsif , else statements there are few points to keep in mind.
•An if can have zero or one else's and it must come after any elsif's.
•An if can have zero to many elsif's and they must come before the else.
•Once an elsif succeeds, none of the remaining elsif's or else's will be tested.
if...elsif...else
• The syntax of an if...elsif...else statement in Perl programming language is −
if(boolean_expression 1) {
# Executes when the boolean expression 1 is true
} elsif( boolean_expression 2) {
# Executes when the boolean expression 2 is true
} elsif( boolean_expression 3) {
# Executes when the boolean expression 3 is true
} else {
# Executes when the none of the above condition is true
}
• The syntax of a while loop in Perl programming language is −
while(condition)
{
statement(s);
}
e.g.

$a = 10;
# while loop execution
while( $a < 20 ) {
printf "Value of a: $a\n";
$a = $a + 1;
}
Syntax:
do {
statement(s);
}while( condition );
for ( init; condition; increment/decrement ) {
statement(s);
}
# for loop execution

for( $a = 10; $a < 20; $a = $a + 1 )


{
print "value of a: $a\n";
}
foreach var (list) {
...
}
foreach $i (1 .. 10)
{
$i_square = $i*$i;
$i_cube= $i*$i*$i;
print “$i\t$i_square\t$i_cube\n";
}

foreach $i reverse(1..10)
{....
...
}
• The most commonly used special variable is $_, which contains the default input and
pattern-searching string. For example, in the following lines −

foreach ('hickory','dickory','doc') {
print $_;
print "\n";
}
When executed, this will produce the following
result −
hickory
dickory
doc
foreach ('hickory','dickory','doc')
{
print;
print "\n";
}
When executed, this will also produce the following result
hickory
Dickory
doc
until
• An until loop statement repeatedly executes a target statement as
long as a given condition is false.
Syntax
until(condition)
{
statement(s);
}
$a = 5;
# until loop execution
until( $a > 10 ) {
printf "Value of a: $a\n";
$a = $a + 1;
}
• Unless,unless..else
Syntax
unless(boolean_expression)
{
# statement(s) will execute if the given condition is false
}

e.g.
$a = 5;
unless( $a > 10 ) {
printf "Value of a is less than 10";
}
unless(boolean_expression) {
# statement(s) will execute if the given condition is false
}
else {
# statement(s) will execute if the given condition is true
}

e.g.
$a = 15;
unless( $a > 10 ) {
printf "Value of a is less than 10";
}
else
{
print ”value of a is greater than 10” ;
}
unless...elsif...else
unless(boolean_expression 1){
# Executes when the boolean expression 1 is false}
elsif( boolean_expression 2){
# Executes when the boolean expression 2 is true}
elsif( boolean_expression 3){
# Executes when the boolean expression 3 is true}
else{
# Executes when the none of the above condition is met
}
switch
• A switch statement allows a variable to be tested for equality against a list of
values. Each value is called a case, and the variable being switched on is
checked for each switch case.

• A switch case implementation is dependent on Switch module and Switch


module has been implemented using Filter::Util::Call and Text::Balanced
and requires both these modules to be installed.
• In order to use switch statement first we should install switch
module.
• Following are the steps to install
1.Open the command prompt.
2.Enter in to perl directory
3.Type the command cpan .
4.At the prompt cpan> , type install Switch .
5.Once completed, Type exit .
use Switch;
switch(argument) {
case 1 { print "number 1" }
case "a" { print "string a" }
case [1..10,42] { print "number in list" }
case (\@array) { print "number in list" }
case /\w+/ { print "pattern" }
case qr/\w+/ { print "pattern" }
case (\%hash) { print "entry in hash" }
case (\&sub) { print "arg to subroutine" }
else { print "previous case not true" }
}
#!/usr/local/bin/perl
use Switch;
$var = 10;
@array = (10, 20, 30);
%hash = ('key1' => 10, 'key2' => 20);
switch($var)
{
case 10 { print "number 100\n" }
case "a" { print "string a" }
case [1..10,42] { print "number in list" }
case (\@array) { print "number in list" }
case (\%hash) { print "entry in hash" }
else { print "previous case not true" }
}

o/p
number 100
Loop Control Statements
• Perl provides three loop control commands
• Loop control statements change the execution from its normal sequence.
• They are next, Last , continue, redo and goto.
• next statement Causes the loop to skip the remainder of its body and
immediately retest its condition prior to reiterating.
• The syntax of a next statement in Perl is −
next [ LABEL ];
• A LABEL inside the square braces indicates that LABEL is optional and if a
LABEL is not specified, then next statement will jump the control to the next
iteration of the nearest loop.
$a = 10;
while( $a < 20 ) {
if( $a == 15) {
# skip the iteration.
$a = $a + 1;
next;
}
print "value of a: $a\n";
$a = $a + 1;
}
C:\Strawberry>perl next1.pl
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 16
value of a: 17
value of a: 18
value of a: 19
• last statement terminates the loop statement and transfers execution
to the statement Immediately following the loop.
• The syntax of a last statement in Perl is −
last [LABEL];
$a = 10;
while( $a < 20 ) {
if( $a == 15) {
# terminate the loop.
$a = $a + 1;
last;
}
print "value of a: $a\n";
$a = $a + 1;
}
C:\Strawberry>perl last1.pl
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
• continue statement A continue BLOCK, it is always executed just before the condition
is about to be evaluated again.
• The syntax for a continue statement with while loop is as follows −
while(condition) {
statement(s);
} continue {
statement(s);
}
e.g. $a = 0;
while($a < 3) {
print "Value of a = $a\n";
} continue {
$a = $a + 1;
}
• The syntax for a continue statement with foreach loop is as follows −
foreach $a (list) {
statement(s);
} continue {
statement(s);
}
e.g.
foreach $a (1,2,3,4,5) {
print "Value of a = $a\n";
} continue {
last if $a == 4;
}
• redo statement: The redo command restarts the loop block without
evaluating the conditional again. The continue block, if any, is not
executed.
• The syntax for a redo statement is as follows −
redo [LABEL]
$a = 1;
# Assigning label to loop
GFG: {
$a = $a + 5;
redo GFG if ($a < 10);
}
# Printing the value
print ($a);
$a = 0;
while($a < 10) {
if( $a == 5 ) {
$a = $a + 1;
redo;
}
print "Value of a = $a\n";
} continue {
$a = $a + 1;
}
• goto statement:Perl supports a goto command with three forms: goto
label, goto expr, and goto &name.
• The syntax for a goto statements is as follows −
goto LABEL
or
goto EXPR
or
goto &NAME
e.g. goto LABEL
$a = 10;
LOOP:do {
if( $a == 15) {
# skip the iteration.
$a = $a + 1;
# use goto LABEL form
goto LOOP;
}
print "Value of a = $a\n";
$a = $a + 1;
} while( $a < 20 );
e.g. goto expression
$a = 10;
$str1 = "LO";
$str2 = "OP";
LOOP:do {
if( $a == 15) {
# skip the iteration.
$a = $a + 1;
# use goto EXPR form
goto $str1.$str2;
}
print "Value of a = $a\n";
$a = $a + 1;
} while( $a < 20 );
Input/output
- output function is print and printf
- input function is <STDIN>
e.g $line=<STDIN>;
Assigns the next line of input to variable $line as a string, complete
with the trailing newline.
- we can use chomp function to remove newline
$line=<STDIN>;
chomp($line); or chomp($line=<STDIN>));
-chomp function removes the line ending character(s) as defined in
$/.
print “enter a line”;
$line=<STDIN>;
chomp($line);
print $line;
o/p
C:\Strawberry\perl>perl in.pl
Enter a line
hello world
hello world
C:\Strawberry\perl>
Print “enter a line”;
$line=<STDIN>;
print $line;

o/p C:\Strawberry\perl>perl in.pl


Enter a line
hello
hello

C:\Strawberry\perl>
# Asking user for Input
print "What is your age?\n";
# Getting an age from the user
$age = <STDIN>;
# Removes new line from the input
chomp $age;
# Printing the value entered by user
print "Your age is ", $age;
lists
-A list is a collection of variables, constants, or expressions , which
is to be treated as a whole.
- it is written as a comma separated sequence of values .
e.g. “red”,”green”,”blue”
1,2,3,4
$a,$b,$c
$a+$b,$a*$b,$a/$b
- a list often appears in a script enclosed in round brackets
e.g. (1,2,3,4,5)
- range operator can also be used in list
(1..8), (“a”..”h”,”o”..”z”)
-list can be as long as needed & they can contain any scalar
values
(1,8.9,”hi”,3)
-list can also have no elements at all & called as empty list
e.g. ()
- a list with one element & a scalar value are different
e.g. 67.3 & (67.3) are different
- a scalar variable name can always be included as pat of a
list.
e.g. (15,$v,”string”) if $v=30
- to save tedious typing we have
qw( the quick brown fox) is a shorthand
for
(“the”,”quick”,”brown”,”fox”)
qw is 'quote word' operator is an extension of the q
& qq.

- list can also be used to make multiple assignments


simultaneously
e.g. ($a,$b,$c)= (1,2,3);
($a,$b)= ($b,$a);
($b,$c,$a)=($a,$b,$c);
arrays
- An array is an ordered collection of data whose components are identified
by an ordinal index.
-the name of an array always starts with @
- the association between array & list is a close one.
e.g.
@arr=(1,2,3,4);

-Where arr is an array variable & (1,2,3,4) is known as list.


- the elements of an array arr can be accessed individually as $arr[0],$arr[1]
and so on.
@arr=(1,2,3,4,"hi","a");
print "\t@arr";
print $arr[4];
- an array can occur as an element of another array
e.g. @f=(3,4,5,6);
@g=(1,2,@f,7,8);

- we can also assign element of an array to the scalar


variable.
$a=$f[1];
$a=$f[4] #will assign null string to a

- @a=(1,2,3,4)
$a[6]=7 then @a will be (1,2,3,4,” “,“ ”, 7).
-you can retrieve length of an array as follows
e.g. @b=(1,2,3,4);
$len=@b; #will give length of list as 4
print $len;

Or

@arr=(1,2,3,4,"hi","a");
print "\t@arr";
print scalar @arr

-The value returned will always be the physical size of the


array, not the number of valid elements.
if we write
$s=(10,20,30) ; #will assign 30 to $s
($s)=@b; #will assign first element of
array b to s.
So $s is a scalar variable & ($s) is a one element list

e.g. $s=(10,20,30) ; print "$s\n";


@b=(10,20,30);
($s)=@b;
print "$s\n";
($s,$s1)=@b;
print "$s $s1“;
@f=(1,2,3,4);
$n=@f;
print " array f has $n elements\n";
print "array f has @f elements\n";
print "array f has ",scalar @f," elements" ;
A program that reads data into an array and writes
print"Enter elements of array";
@a=<STDIN>;
print"@a";

C:\Strawberry>arr3.pl
Enter elements of array8
4
34
"hi"
'g'
6.7
^Z
8
4
34
"hi"
'g'
6.7
Using array slices
-perl enable you to access more than one
element of an array at a time.
e.g. @arr=(1,2,3,4,5)
@subarr=@arr[0,1];
- Here @arr[0,1] refers to first two elements of
the list. This portion of array is known as Array
Slice
So @subarr will be 1,2
- e.g @subarr=@arr[0..3];
@array = ("one", "two", "three", "four", "five");
@range = (1, 2, 3);
@subarray = @array[@range];
print ("The array slice is: @subarray\n");
Adding and Removing
Elements in Array
Perl provides several built-in functions for array
manipulation.
- shift LIST : returns the first item of LIST, and moves the remaining
items down reducing the size of LIST by -1
-unshift ARRAY,LIST : the opposite of shift. Puts the items in LIST at
the beginning of ARRAY,moving the original contents up by the
required amount.
-push ARRAY,LIST : similar to unshift, but adds the values in LIST to
the end of ARRAY.
-pop @ARRAY :Pops off and returns the last value of the array.
@names = ('Foo', 'Bar', 'Moo');
$first = shift @names;
print "$first\n"; # Foo
print "@names\n"; # Bar Moo
Shift Example
#!/usr/bin/perl
@array = (1..5);
while ($element = shift(@array))
{ print("$element ");
}
print("The End\n");
Unshift example
#!/usr/bin/perl
@array = ( 1, 2, 3, 4);
print "Value of array is @array\n" ;
unshift @array, 20, 30, 40 ;
print "Now value of array is @array\n" ;

When above code is executed, it produces the following


result −
Value of array is 1 2 3 4
Now value of array is 20 30 40 1 2 3 4
@names = ('Foo', 'Bar');
unshift @names, 'Moo';
print "@names\n"; # Moo Foo Bar
@others = ('Darth', 'Vader');
unshift @names, @others;
print "@names\n"; # Darth Vader Moo Foo Bar
Push example
@names = ('Foo', 'Bar');
push @names, 'Moo';
print "@names\n"; # Foo Bar Moo
@others = ('Darth', 'Vader');
push @names, @others;
print "@names\n"; # Foo Bar Moo Darth Vader
Pop example
@names = ('Foo', 'Bar', 'Baz');
$last_one = pop @names;
print "$last_one\n"; # Baz
print "@names\n"; # Foo Bar
@array = (1,2,3);
$a=@array;
print "\$a is $a\n";
print "Size:", scalar @array,"\n";
print “array elements are @array\n";
print “array elements are scalar @array\n";
print " array \@array has $a elements\n";
print "array \@array has @array elements\n";

C:\Strawberry>perl arrsize.pl
$a is 3
Size:3
array elements are scalar 1 2 3
array elements are scalar 1 2 3
array @array has 3 elements
array @array has 1 2 3 elements
Replacing Array Elements
splice(),
syntax −
splice @ARRAY, OFFSET [ , LENGTH [ , LIST ] ]

#!/usr/bin/perl
@nums = (1..20);
print "Before - @nums\n";
splice(@nums, 5, 5, 21..25);
print "After - @nums\n";
This will produce the following result −
Before - 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
After - 1 2 3 4 5 21 22 23 24 25 11 12 13 14 15 16 17 18 19 20
Reversing a List or Array Variable

The syntax for the reverse library function is

retlist = reverse (array);


array is the list to reverse, and retlist is the reversed list.

Here is an example:

@array = ("backwards", "is", "array", "this");


@array2 = reverse(@array);
print "@array\n";
print "@array2";
Sorting a List or Array
Variable
The library function sort sorts the elements of an array in alphabetical order
and returns the sorted list.
The syntax for the sort library function is
sortarr = sort (array);
In this syntax, array is the list to sort, and sortarr is the sorted list.
@array = ("this", "is", "a", "test");
@array2 = sort (@array);
After sort is called, the value of @array2 is the list ("a", "is", "test", "this")
Note that sort treats its items as strings, not integers; items are sorted
in alphabetical, not numeric, order. For example:
@array = (70, 100, 8);
@array = sort (@array);

In this case, sort produces


(100, 70, 8)

not
(8, 70, 100)

@sorted_numbers = sort { $a <=> $b } @array;


print “ @sorted_numbers\t”; //8,70,100
e.g.
@array=(70,100,85,35,6,8);
@sorted_numbers = sort { $a <=> $b } @array;
print "@sorted_numbers\t";

C:\Strawberry>perl arrsort.pl
6 8 35 70 85 100
C:\Strawberry>
Merging Arrays

• Because an array is just a comma-separated sequence of values, you


can combine them together as shown below −

#!/usr/bin/perl
@numbers = (1,3,(4,5,6));
print "numbers = @numbers\n";

This will produce the following result −


numbers = 1 3 4 5 6
#!/usr/bin/perl
@odd = (1,3,5);
@even = (2, 4, 6);
@numbers = (@odd, @even);
print "numbers = @numbers\n";

This will produce the following result −


numbers = 1 3 5 2 4 6
Selecting Elements from Lists
• The list notation is identical to that for arrays. You can extract an
element from a list by appending square brackets to the list and
giving one or more indices

#!/usr/bin/perl
$var = (5,4,3,2,1)[4];
print "value of var = $var\n"
This will produce the following result −
value of var = 1
Similarly, we can extract slices, although without the requirement for a
leading @ character −
#!/usr/bin/perl
@list = (5,4,3,2,1)[1..3];
print "Value of list = @list\n";

This will produce the following result −


Value of list = 4 3 2
Iterating over list
- foreach loop performs a simple iteration over all the elements of a list
e.g. foreach $item(list){...
}
- The variable can be omitted in which case $- will be used
-since perl will automatically converts an array into a list for manipulating all the items
in an array we can use
foreach (@array){
#Process $_;
}
For e.g. we can reverse the sign of every element in an array of numbers as follows
foreach (@a){
$_= - $_;
}
The $[ Special Variable
• We have a special variable, which is written as $[.
• This special variable is a scalar containing the first index of all arrays.
• Because Perl arrays have zero-based indexing, $[ will almost always be 0.
• But if you set $[ to 1 then all your arrays will use one-based indexing.
#!/usr/bin/perl
# define an array
@foods = qw(pizza steak chicken burgers);
print "Foods: @foods\n";
# Let's reset first index of all the arrays.
$[ = 1;
print "Food at \@foods[1]: $foods[1]\n";
print "Food at \@foods[2]: $foods[2]\n";

This will produce the following result


Foods: pizza steak chicken burgers
Food at @foods[1]: pizza
Food at @foods[2]: steak
Hashes
- Hashes are unordered sets of key/value pairs that you access using
the keys as subscripts.
-Hash is also known as associative array or content addressable
array.
-Is one in which each element has two components, a key & a value
-To refer to a single element of a hash, you will use the hash variable
name preceded by a "$" sign and followed by the "key" associated
with the value in curly brackets.
-Such array is usually stored in a hash table to facilitate efficient
retrieval.
Creating Hashes

%f=(key1,val1,key2,val2.......); or
%f=(key1=>val1,key2=>val2.......);
e.g.
%f= ( banana,yellow,apple,red);
%f= ( banana=>'yellow',apple=>'red',....);
or
$f{‘banana’} = yellow;
$f{‘apple'} = red;
……
#!/usr/bin/perl
%data = ('John Paul', 45, 'Lisa', 30, 'Kumar', 40);
print "\$data{'John Paul'} = $data{'John Paul'}\n";
print "\$data{'Lisa'} = $data{'Lisa'}\n";
print "\$data{'Kumar'} = $data{'Kumar'}\n";
print %data;

This will produce the following result −


C:\Strawberry>perl hash1.pl
$data{'John Paul'} = 45
$data{'Lisa'} = 30
$data{'Kumar'} = 40
Lisa30Kumar40John Paul45
C:\Strawberry>
Extracting Slices
You can extract slices of a hash just as you can extract slices from an
array. You will need to use @ prefix for the variable to store the returned
value because they will be a list of values −

#!/usr/bin/perl
%data = (JohnPaul => 45, Lisa => 30, Kumar =>
40);
@array = @data{JohnPaul,Lisa};
print "Array : @array\n";
$a=$data{Kumar};
print $a;
Extracting Keys and Values
- if you have hash called magic then
Keys %magic #returns a list of the keys of the elements in the hash
Values %magic #returns a list of the values of the elements in the hash
-these functions provide a convenient way to iterate over the elements of hash using
foreach
foreach $k (keys %magic)
{ do something with $magic{$k};
}

foreach (keys %magic)


{ do something with $magic{$_};
}
%magic=(a=>1,b=>2,c=>3);
foreach $k(keys %magic)
{
print $magic{$k};
}
!/usr/bin/perl
%data = ('John Paul' => 45, 'Lisa' => 30, 'Kumar' =>
40); @names = keys %data;
print “@names\n";

This will produce the following result −


Lisa John Paul Kumar
#!/usr/bin/perl
%data = ('John Paul' => 45, 'Lisa' => 30, 'Kumar' =>
40);
@ages = values %data;
print "$ages[0]\n";
print "$ages[1]\n";
print "$ages[2]\n";

This will produce the following result −


30
45
40
-an alternative approach is to use each operator which delivers successive key-
value pairs from a hash.
e.g. while(($key,$value)=each %magic)
{ print $key->$value}

%data = (JohnPaul => 45, Lisa => 30, Kumar => 40);
while(($key,$value)=each(%data))
{
print "\n$key => $value";
}

C:\Strawberry>hash1.pl

JohnPaul=>45
Lisa=>30
Kumar=>40
C:\Strawberry>
• -other useful operators are delete & exists.
delete $magic{$key}
• removes the element whose key matches $key from the hash
%magic
exists $magic{$key};
• Returns true if the hash %magic contains an element whose key
matches $key.
$prices{"pizza"} = 12.00;
$prices{"coke"} = 1.25;
$prices{"sandwich"} = 3.00;
while (($key, $value) = each (%prices))
{
print "$key costs $value\n";
}
C:\Strawberry>hash5.pl
coke costs 1.25
sandwich costs 3
pizza costs 12
C:\Strawberry>
#!/usr/bin/perl
# create our perl hash
$prices{"pizza"} = 12.00;
$prices{"coke"} = 1.25;
$prices{"sandwich"} = 3.00;
# print the hash key and value using a foreach loop
foreach $key (keys %prices)
{
print "$key costs $prices{$key}\n";
}
!/usr/bin/perl
%data = ('John Paul' => 45, 'Lisa' => 30, 'Kumar' =>
40);
if( exists($data{'Lisa'} ) )
{
print "Lisa is $data{'Lisa'} years old\n";
}
else{
print "I don't know age of Lisa\n";
}
Getting Hash Size
#!/usr/bin/perl
%data = ('John Paul' => 45, 'Lisa' => 30, 'Kumar' => 40);
@keys = keys %data;
$size = @keys;
print "1 - Hash size: is $size\n";
@values = values %data;
$size = @values;
print "2 - Hash size: is $size\n";
$size=%data;
print $size;
Add and Remove Elements in
Hashes

• Adding a new key/value pair can be done with one line of code using
simple assignment operator.
• But to remove an element from the hash you need to use delete
function as shown below in the example −
#!/usr/bin/perl
%data = ('John Paul' => 45, 'Lisa' => 30, 'Kumar' =>
40);
$size = %data;
print "1 - Hash size: is $size\n";
# adding an element to the hash;
$data{'Ali'} = 55;
$size = %data;
print "2 - Hash size: is $size\n";
# delete the same element from the hash;
delete $data{'Ali’};
$size = %data;
print "3 - Hash size: is $size\n";
This will produce the following result −
1 - Hash size: is 3
2 - Hash size: is 4
3 - Hash size: is 3
-Inverting a hash
e.g %by_no= reverse %phones;
With this keys will become values and values will
become keys.
e.g.
%magic=(1=>7,b=>2,c=>4);
print %magic;
%magic1=reverse %magic;
print %magic1;

C:\Strawberry>hash9.pl
c417b2712b4c
C:\Strawberry>
Strings
• Strings are an essential part of the Perl language. They are scalar
variables, so they start with ($) sign. A string can be defined within a
single quote (') or double quote (").
• Apart from single quote and double quote we can use q, qq, qw and
qx quote like operators which allows us to take any non-alphabetic
and non-numeric characters as the delimiters.
Perl string functions
• Perl provides a set of functions that allow you to manipulate strings
effectively.
1. Perl string length
• To find the number of characters in a string, you use the length()
function. See the following example:

my $s = "This is a string\n";
print(length($s),"\n"); #17
2. Changing cases of string
•To change the cases of a string you use a pair of functions lc() and
uc() that returns the lower case and upper case versions of a string.

my $s = "Change cases of a string\n";


print("To upper case:\n");
print(uc($s),"\n");
print("To lower case:\n");
print(lc($s),"\n");
3. Search for a substring inside a string
•To search for a substring inside a string, you use index() and rindex()
functions.
• The index() function searches for a substring inside a string from a
specified position and returns the position of the first occurrence of the
substring in the searched string. If the position is omitted, it searches
from the beginning of the string.
• The rindex() function works like the index() function except it
searches from the end of the string instead of from the beginning.
E.g.
my $s = "Learning Perl is easy\n";
my $sub = "Perl";
my $p = index($s,$sub); # rindex($s,$sub);
print(qq\The substring "$sub" found at position "$p" in string "$s"\,"\
n");
• Get or modify substring inside a string
• To extract a substring out of a string, you use the substr() function.
• E.g.
# extract substring
my $s = "Green is my favourite color";
my $color = substr($s, 0, 5); # Green
my $str = substr($s,5); #is my favourite color
my $str1 = substr($s,5,10); #is my fav
my $end = substr($s, -5); # color
# replace substring
substr($s, 0, 5, "Red"); #Red is my favourite color
print($s,"\n");
Subroutines
• A Perl subroutine or function is a group of statements that together
performs a task.
• You can divide up your code into separate subroutines. How you divide
up your code among different subroutines is up to you, but logically the
division should be such that each function performs a specific task.
• Perl uses the terms subroutine, method and function interchangeably.
• Perl program executes this body of code by calling or invoking the
subroutine;
• The act of invoking a subroutine is called a subroutine invocation.

-
Syntax:
sub subroutine_name
{
# body of method or subroutine
}
e.g
sub add {
Statements;
}

-subroutine definition does not include argument specification; it just


associates the name with the block
• The typical way of calling the Perl subroutine is as follows −
subroutine_name( list of arguments );
• In versions of Perl before 5.0, the syntax for calling subroutines was
slightly different as shown below.
&subroutine_name( list of arguments );
• This still works in the newest versions of Perl, but it is not
recommended since it bypasses the subroutine prototypes.
# Function definition
sub Hello {
print "Hello, World!\n";
}
# Function call
Hello();

When above program is executed, it produces the following result −


Hello, World!
&add; or &add(); //subroutine call

&getnumbers; #Subroutine Call


print ("@a”);
#Subroutine Definition
sub getnumbers {
print "Enter array elements";
@a= <STDIN>;
chomp(@a);
}
Forward References to
Subroutines
sub readaline {

$line = <STDIN>;

...

readaline;
sub readaline; # Subroutine Declaration

...

readaline; # Subroutine call

...

sub readaline { # Subroutine Definition

$line = <STDIN>;

}
Subroutine arguments
- if a subroutine expects argument the call takes the form
&add(arg1,arg2);
-if a subroutine is already declared we can omit &.
add(arg1,arg2); or add arg1,arg2
-a subroutine expects to find its arguments as a single flat list of scalars in the
anonymous array @_: they can be accessed in the body as $_[0],$_[1] ..etc.
-so if we write
add arg1,arg2;
The effect is as if the assignment
@_=(arg1,arg2);
sub area
{
# passing argument
$side = $_[0];
$a=$side*$side;
print “ area of rectangle is $a” ;
}
# calling function
area(4);
#@_=(4);
print “enter 1st no”;
$a=<STDIN>;
Print “enter 2nd number”;
$b=<stdin>;
&add($a,$b); #@_=($a,$b);
sub add
{
$a=$_[0];
$b=$_[1];
$c=$a+$b;
print “Addition is $c”;
}
Passing Lists to Subroutines
•Because the @_ variable is an array, it can be used to supply lists to a
subroutine.
•E.g.
# Function definition
sub PrintList {
my @list = @_;
print "Given list is @list\n";
}
$a = 10;
@b = (1, 2, 3, 4);
# Function call with list parameter
PrintList($a, @b);
Passing a List to a Subroutine
If you want, you can pass a list to a subroutine. For example, the following subroutine adds the elements of a list together and prints the
result:

sub addlist {
my (@list) = @_;
$total = 0;
foreach $item (@list) {
$total += $item;
}
print "The total is $total\n";
}
To invoke this subroutine, pass it an array variable, a list, or any combination of lists and
scalar values.

@mylist=(12,10,20);
addlist (@mylist);
or
addlist (“14", "6", "11"); or addlist (14, 6, 11);
Passing Hashes to Subroutines
•When you supply a hash to a subroutine or operator that accepts a list, then
hash is automatically translated into a list of key/value pairs. For example −
# Function definition
sub PrintHash {
my (%hash) = @_;
foreach my $key ( keys %hash ) {
my $value = $hash{$key};
print "$key : $value\n";
}
}
%hash = ('name' => 'Tom', 'age' => 19);
# Function call with hash parameter
PrintHash(%hash);
The return Statement
The syntax for the return statement is
return (retval);

- the value returned by a subroutine may be scalar or a


single flat list of scalars.
e.g. $x=add ($a,$b);
@x=series($a,$b,$c);
sub area
{
# passing argument
$side = $_[0];
return ($side * $side);
}
# calling function
$totalArea = area(4);
# displaying result
printf $totalArea;
sub addmul
{
# passing argument
$side = $_[0];
return ($side * $side, $side + $side);
}
# calling function
@totalArea = addmul(5);
# displaying result
print "@totalArea";
sub Mul()
{
my($a, $b ) = @_;
my $c = $a * $b;
# Return Value
return($a, $b, $c);
}
# Calling in Scalar context
$retval = Mul(25, 10);
print ("Return value is $retval\n" );
# Calling in list context
@retval = Mul(25, 10);
print ("Return value is @retval\n" );
C:\Strawberry>suretmulval.pl
25 10
C:\Strawberry>subret2.pl
Return value is 250
Return value is 25 10 250
Using Local Variables in
Subroutines
• By default, all variables in Perl are global variables, which means they can be accessed from
anywhere in the program.
• But you can create private variables called lexical variables at any time with the my operator.
• The my operator confines a variable to a particular region of code in which it can be used and
accessed.
• Outside that region, this variable cannot be used or accessed. This region is called its scope.
• A lexical scope is usually a block of code with a set of braces around it, such as those defining the
body of the subroutine or those marking the code blocks of if, while, for, foreach, and eval
statements.
• In Perl 5, there are two statements used to define local variables:
 my statement, which defines variables that exist only inside a subroutine.
 local statement, which defines variables that do not exist inside the main program, but inside the subroutine
and any subroutines called by the subroutine.

• In Perl 4, my statement is not defined, so you must use local to define a variable that is not known
to the main program.
e.g. sub s{
my $f,my $b;
my ($a,$c,@h);
}

Initializing Local Variables

sub my_sub {
my($scalar) = 43;
my(@array) = ("here's", "a", "list");
# code goes here
}
#!/usr/local/bin/perl
$a=6;
$b=9;
$c=10;
&add($a,$b);
sub add {
my $c;
$c=$_[0]+$_[1];
print("$c");
}
print("$c");
$a=10;
sub hello
{
local $a=$_[0];
print "inside hello $a";
&hi;
}
hello(5);
print "\n outside sub:$a";
sub hi
{
print "\ninside hi $a";
}
C:\Strawberry>sublocal.pl
inside hello 5
inside hi 5
outside sub:10
$a=10;
sub hello
{
Output:
my $a=$_[0];
print "inside hello $a"; C:\Strawberry>sublocal.pl
&hi;
inside hello 5
}
hello(5); inside hi 10
print "\n outside sub:$a";
outside sub:10
sub hi
{
print "\n inside hi $a";
}
A program containing a subroutine in the middle of the main program.

while (1) {
&readaline;
last if ($line eq "");
sub readaline {
$line = <STDIN>;
}
print ($line);
}
print ("done\n");
Patterns & Regular Expression
• A regular expression is a string of characters that defines the
pattern.
• The syntax of regular expressions in Perl is very similar to
what you will find within other regular expression.
• Regular expressions provide an extremely powerful way of
defining patterns.
• The RE cab be built up using the metacharacters
\ | ( ) [ { ^ $ * + ? . ], } etc.
-A pattern is a sequence of characters to be searched for in a
character string.
-In Perl, patterns are normally enclosed in slash characters:
/def/ #This represents the pattern def.
-If the pattern is found, a match occurs. For example, if you search
the string redefine for the pattern /def/, the pattern matches
the third, fourth, and fifth characters of Redefine
Regular Expression operators

There are three regular expression operators within Perl.


•Match Regular Expression - m//
•Substitute Regular Expression - s///
•Transliterate Regular Expression – tr///

•The forward slashes in each case act as delimiters for the regular
expression (regex) that you are specifying. If you are comfortable with
any other delimiter, then you can use in place of forward slash.
• The Match Operator
• m//, is used to match a string or statement to a regular expression.
• You can omit m from m// if the delimiters are forward slashes, but for all other delimiters
you must use the m prefix.
• E.g.
$bar = "This is foo and again foo";
if ($bar =~ m{foo}) # =~ is test and assignment operator
{
print “Match is found\n";
}
else
{
print “Match not found\n";
}
• E.g.
$bar = "This is foo and again foo";
if ($bar =~ /foo/) # =~ is test and assignment operator
{
print “Match is found\n";
}
else
{
print “Match not found\n";
}
Match Operator Modifiers
When you specify a pattern, you can also supply
options that control how the pattern is to be
matched. Following represents pattern-matching
modifiers.
Description options

Match all possible patterns g

Ignore case i
Treat string as multiple lines m
Only evaluate once o
Treat string as single line s
Ignore white space in pattern x
All pattern options are included immediately after the pattern. For example, the following
pattern uses the i option to ignore case:
/ab*c/i
You can specify as many of the options as you like, and the options can be in any order.

e.g.
$bar = "This is FOO";
if ($bar =~ /foo/i) # =~ is test and assignment operator
{
print "Match is found\n";
}
else
{
print "Match not found\n";
}
• Regular Expression Variables
• Regular expression variables include $, which contains whatever the
last grouping match matched; $&, which contains the entire matched
string; $`, which contains everything before the matched string; and
$', which contains everything after the matched string.

$string = "The food is in the salad bar";


$string =~ /foo/;
print "Before: $`\n";
print "Matched: $&\n";
print "After: $'\n";
Output :
C:\Strawberry>regexp4.pl
Before: The
Matched: foo
After: d is in the salad bar
• The Substitution Operator

• The substitution operator, s///, is really just an extension of the


match operator that allows you to replace the text matched with
some new text. The basic form of the operator is −

s/PATTERN/REPLACEMENT/;

• The PATTERN is the regular expression for the text that we are
looking for. The REPLACEMENT is a specification for the text or
regular expression that we want to use to replace the found text
with.
• For example, we can replace all occurrences of dog with cat using the
following regular expression −

$string = "The cat sat on the mat";


$string =~ s/cat/dog/;
print "$string\n";

• Output
C:\Strawberry>regexp5.pl
The dog sat on the mat
Subtitute Operator Modifiers

Description
options

Replaces all occurrences of the found expression with the replacement text.
g
Ignore case i
Treat string as multiple lines
m
Only evaluate once
o
Treat string as single line
s
Ignore white space in pattern
x
$string = "The cat sat cat on the mat";
$string =~ s/cat/dog/g ;
print "$string\n";

•Output:
•:\Strawberry>regexp5.pl
The dog sat dog on the mat
• The Translation Operator
• Translation is similar, but not identical, to the principles of substitution,
but unlike substitution, translation (or transliteration) does not use
regular expressions for its search on replacement values. The translation
operators are −

• tr/SEARCHLIST/REPLACEMENTLIST/
• y/SEARCHLIST/REPLACEMENTLIST/

• The translation replaces all occurrences of the characters in SEARCHLIST


with the corresponding characters in REPLACEMENTLIST.
• E.g.
$string = 'The cat sat on the mat';
$string =~ tr/a/o/;
print "$string\n";

When above program is executed, it produces the following result −

The cot sot on the mot.


• Standard Perl ranges can also be used, allowing you to specify ranges
of characters either by letter or numerical value.
• To change the case of the string, you might use the following syntax
in place of the uc function.

$string =~ tr/a-z/A-Z/;
• Translation Operator Modifiers
• Following is the list of operators related to translation.
• Sr.No. Modifier & Description
1 c Complements SEARCHLIST.
2 d Deletes found but unreplaced characters.
3 s Squashes duplicate replaced characters.
• the /d modifier deletes the characters matching SEARCHLIST that do
not have a corresponding entry in REPLACEMENTLIST. For example −

$string = 'the cat sat on the mat.';


$string =~ tr/a-j/b/d;
print "$string\n";

When above program is executed, it produces the following result −


C:\Strawberry>regexp6.pl
t bt sbt on t mbt.
• The last modifier, /s, removes the duplicate sequences of characters that were
replaced, so −

$string = 'food';
$string = 'food';
$string =~ tr/a-z/A-Z/s;
print "$string\n";

• When above program is executed, it produces the following result −


C:\Strawberry>regexp7.pl
FOD
• More Complex Regular Expressions
• You don't just have to match on fixed strings. In fact, you can match on just about
anything you could dream of by using more complex regular expressions.
• A Regular Expression contains one or more of the following:
• A character set:
The simplest type of Regular Expression consists only of a character set, with
no metacharacters.
• An anchor:
These designate (anchor) the position in the line of text that the RE is to
match. For example, ^, and $ are anchors.
• Modifiers:
Modifiers include the asterisk, brackets, and the backslash.
e.g. \ | ( ) [ { ^ $ * + ? . ], }
Special Characters in
Patterns
• Perl supports a variety of special characters inside patterns, which enables you to
match any number of character strings. These special characters make patterns
useful.

The + Character

The special character + means "one or more occurrence of the preceding characters."
For example, the pattern /de+f/ matches any of the following:

def
deef
deeef
deeeeeeef
The * and ? Special
Characters
-The * special character matches zero or more occurrences of the preceding character.
For example, the pattern
/de*f/
matches df, def, deef, and so on.

-The ? character matches zero or one occurrence of the preceding character. For
example, the pattern
/de?f/
-matches either df or def.
- Note that it does not match deef, because the ? character does not match two
occurrences of a character.
The ^ and $ Pattern
Anchors
-The pattern anchors ^ and $ ensure that the pattern is matched only at the
beginning or the end of a string. For example, the pattern
/^def/
matches def only if these are the first three characters in the string.
Similarly, the pattern
/def$/
matches def only if these are the last three characters in the string.
-You can combine ^ and $ to force matching of the entire string, as follows:
/^def$/
This matches only if the string is def.
The [ ] Special Characters

The [] special characters enable you to define


patterns that match one of a group of
alternatives. For example, the following pattern
matches def or dEf:
/d[eE]f/
-You can specify as many alternatives as you like.
/a[0123456789]c/
This matches a, followed by any one digit,
followed by c.
/[0-9]/ /[a-z0-9]/
Matching Any Character
-Another special character supported in patterns is the period
(.) character, which matches any single character except the
newline character.
For example, the following pattern matches d, followed by
any non-newline character, followed by f:
/d.f/
Some more characters in Regular
Expressions
• Perl implements a very rich form of regular expressions with many
enhancements on the basic facilities. Following are the most useful
facilities.
1. Alternations
• If REI, RE2 and RE3 are regular expressions, REI | RE2|RE3 is a regular
expression that will match anyone of the components.
• For example, to match "cat" or "dog" in an expression, you might use this

if ($string =~ /cat|dog/)
2. Grouping
•Round brackets can be used to group items
E.g.
/pitt the (elder|younger)/
•The first of these patterns matches Pitt the elder and Pitt the younger.

3. Repetition counts
•In addition to the quantifiers *, ? And + explicit repetition counts can be
added to component of a regular expression,
e.g. /a{2}/ matches ‘aac’ will not match with ‘aaac’
•The full list of possible count modifiers is:
{n} must occur exactly n times
{n ,} must occur at least n times for e.g /a{3,}/ will not match with ‘aab’
{n,m} must occur at least n times but no more than m times

/a{3,5}/ will not match ‘aaaaaab’


4. Non-greedy matching
•A pattern including . * matches the longest string it can find.
•The pattern . *? can be used when the shortest match is required.

@list = qw/food foosball subeo footnote terfoot canic footbrdige/;


foreach (@list) {
$first = $& if /(foo.*?)/;
$last = $& if /(foo.*)/;
}
print "First: $first, Last: $last\n";

5. Shorthand
•Some character classes occur so often that a shorthand notation is provided:
\ d : matches a digit, e.g if ($str =~ ‘\d’)
\ w : matches a 'word' character (upper-case letter, lower-case letter or digit), and
\ s :matches a 'whitespace' character (space, tab, carriage return or newline).
•Capitalization reverses the sense, e.g. \D matches any non-digit character

You might also like