Unit III Perl
Unit III Perl
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
• 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 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";
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
$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.
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
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.
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;
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.
- @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
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" ;
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
Here is an example:
not
(8, 70, 100)
C:\Strawberry>perl arrsort.pl
6 8 35 70 85 100
C:\Strawberry>
Merging Arrays
#!/usr/bin/perl
@numbers = (1,3,(4,5,6));
print "numbers = @numbers\n";
#!/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";
%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;
#!/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};
}
%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.
-
Syntax:
sub subroutine_name
{
# body of method or subroutine
}
e.g
sub add {
Statements;
}
$line = <STDIN>;
...
readaline;
sub readaline; # Subroutine Declaration
...
...
$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);
• 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);
}
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
•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
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.
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 −
• 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/
$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 = 'food';
$string = 'food';
$string =~ tr/a-z/A-Z/s;
print "$string\n";
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
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
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