SlideShare a Scribd company logo
1
Mr.Anish.L.S Mr.Ravi kumar
2
 Perl is a stable, cross platform programming language.
 It is used for mission critical projects in the public and private
sectors.
 Perl is an Open Source software, licensed under its Artistic
License, or the GNU General Public License (GPL).
 Perl was created by Larry Wall.
INTRODUCTION :
3
4
PERL FEATURES :
 Perl takes the best features from other languages, such as C, awk,
sed, sh, and BASIC, among others.
 Perls database integration interface DBI supports third-party
databases including Oracle, Sybase, Postgres, MySQL and
others.
 Perl works with HTML, XML, and other mark-up languages.
 Perl supports Unicode.
 Perl supports both procedural and object-oriented programming.
 The Perl interpreter can be embedded into other systems.
5
6
PERL INTERPRETED :
 Perl is an interpreted language, which means that your code
can be run as is, without a compilation stage that creates a
non portable executable program.
 Traditional compilers convert programs into machine
language. When you run a Perl program, it's first compiled
into a byte code, which is then converted ( as the program
runs) into machine instructions.
7
8
PERL IDENTIFIERS :
 A Perl identifier is a name used to identify a variable,
function, class, module, or other object.
 A Perl variable name starts with either $, @ or % followed
by zero or more letters, underscores, and digits (0 to 9).
 Perl does not allow punctuation characters such as @, $,
and % within identifiers.
 Perl is a case sensitive programming language.
Example:
 $Manpower and $manpower are two different identifiers
in Perl.
9
10
S.N Types and Description
1
Scalar − Scalars are simple variables. They are
preceded by a dollar sign ($). A scalar is either a
number, a string, or a reference. A reference is
actually an address of a variable, which we will see
in the upcoming chapters.
2
Arrays − Arrays are ordered lists of scalars that
you access with a numeric index which starts with
0. They are preceded by an "at" sign (@).
3
Hashes −Hashes are unordered sets of key/value
pairs that you access using the keys as subscripts.
They are preceded by a percent sign (%).
PERL DATATYPES :
11
STRING LITERALS & ESCAPE SEQUENCE :
 Double-quoted string literals allow variable interpolation.
 single-quoted string literals Doesn’t allow variable
interpolation.
 There are certain characters when they are proceeded by
a back slash, have special meaning and they are used to
represent like newline (n) or tab (t).
12
EXAMPLE PROGRAM :
#!/usr/bin/perl
# This is case of interpolation.
$str = "Welcome to nHybridChipTechnologies.com!";
print "$strn";
# This is case of non-interpolation.
$str = 'Welcome to nHybridChipTechnologies.com!';
print "$strn";
# Only W will become upper case.
$str = "uwelcome to HybridChipTechnologies.com!";
print "$strn";
# Whole line will become capital.
$str = "UWelcome to HybridChipTechnologies.com!";
print "$strn";
# A portion of line will become capital.
$str = "Welcome to UHybridChipTechnologiesE.com!";
print "$strn";
# Backsalash non alpha-numeric including spaces.
$str = "QWelcome to HybridChipTechnologies's family";
print "$strn";
13
Welcome to HybridChipTechnologies.com!
Welcome to nHybridChipTechnologies.com!
Welcome to HybridChipTechnologies.com!
WELCOME TO HYBRIDCHIPTECHNOLOGIES.COM!
Welcome to HYBRIDCHIPTECHNOLOGIES.com!
Welcome to HybridChipTechnologies's family
OUTPUT :
14
15
SCALAR VARIABLES :
 A scalar is a single unit of data. That data might be an integer
number, floating point, a character, a string, a paragraph, or an
entire web page. Simply saying it could be anything, but only a
single thing.
EXAMPLE :
#!/usr/bin/perl
$age = 25;
# An integer assignment
$name = "John Paul";
# A string
$salary = 1445.50;
# A floating point
print "Age = $agen";
print "Name = $namen";
print "Salary = $salaryn";
OUTPUT :
Age = 25
Name = John Paul
Salary = 1445.5
16
17
ARRAY VARIABLES :
 An array is a variable that stores an ordered list of scalar
values. Array variables are preceded by an "at" (@) sign. To
refer to a single element of an array, you will use the dollar sign
($) with the variable name followed by the index of the element
in square brackets.
PROGRAM :
#!/usr/bin/perl
@ages = (25, 30, 40);
@names = ("John Paul", "Lisa", "Kumar");
print "$ages[0] = $ages[0]n";
print "$ages[1] = $ages[1]n";
print "$ages[2] = $ages[2]n";
print "$names[0] = $names[0]n";
print "$names[1] = $names[1]n";
print "$names[2] = $names[2]n";
OUTPUT :
$ages[0] = 25
$ages[1] = 30
$ages[2] = 40
$names[0] = John
Paul $names[1] =
Lisa $names[2] =
Kumar
18
19
HASH VARIABLES :
 A hash is a set of key/value pairs. Hash variables are preceded by a
percent (%) sign. To refer to a single element of a hash, you will use
the hash variable name followed by the "key" associated with the value
in curly brackets.
PROGRAM :
#!/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";
OUTPUT :
$data{'John Paul'} = 45
$data{'Lisa'} = 30
$data{'Kumar'} = 40
20
21
VARIABLE CONTEXT :
 Perl treats same variable differently based on Context, i.e.
situation where a variable is being used.
PROGRAM
#!/usr/bin/perl
@names = ('John Paul', 'Lisa', 'Kumar');
@copy = @names;
$size = @names;
print "Given names are : @copyn";
print "Number of names are : $sizen";
OUTPUT
Given names are : John Paul Lisa Kumar
Number of names are : 3
22
S.N Context and Description
1
Scalar −Assignment to a scalar variable evaluates the
right-hand side in a scalar context.
2
List −Assignment to an array or a hash evaluates the
right-hand side in a list context.
3
Interpolative −This context only happens inside
quotes, or things that work like quotes.
4
Void −This context not only doesn't care what the
return value is, it doesn't even want a return value.
23
24
CONDITIONAL STATEMENTS :
Statement Description
if statement An if statement consists of a boolean expression followed
by one or more statements.
if...else statement An if statement can be followed by an optional else
statement.
if...elsif...else statement An if statement can be followed by an optional elsif
statement and then by an optional else statement.
unless statement An unless statement consists of a boolean expression
followed by one or more statements.
unless...else statement An unless statement can be followed by an optionalelse
statement.
unless...elsif..else
statement
An unless statement can be followed by an optionalelsif
statement and then by an optional else statement.
switch statement With the latest versions of Perl, you can make use of
theswitch statement. which allows a simple way of
comparing a variable value against various conditions.
25
 The number 0, the strings '0' and "" , the empty list () , and undef are all falsein
a boolean context and all other values are true. Negation of a true value
by ! or not returns a special false value.
The syntax of an if statement in Perl programming language is −
if(boolean_expression)
{
# statement(s) will execute if the given condition is true
}
26
OUTPUT
a is less than 20
value of a is : 10
value of a is :
PROGRAM
#!/usr/local/bin/perl
$a = 10;
# check the boolean condition using if statement
if( $a < 20 )
{
# if condition is true then print the following
print "a is less than 20n";
}
print "value of a is : $an";
$a = "";
# check the boolean condition using if statement
if( $a )
{
# if condition is true then print the following
print "a has a true valuen";
}
print "value of a is : $an";
Explanation:
 First IF statement makes use
of less than operator (<),
which compares two
operands and if first operand
is less than the second one
then it returns true otherwise
it returns false.
27
if(boolean_expression){
# statement(s) will execute if the given condition is true }
else{
# statement(s) will execute if the given condition is false }
 The number 0, the strings '0' and "" , the empty list () , and undef are all falsein
a boolean context and all other values are true. Negation of a true value
by ! or not returns a special false value.
28
PROGRAM
#!/usr/local/bin/perl
$a = 100;
# check the boolean condition using if statement
if( $a < 20 ){
# if condition is true then print the following
printf "a is less than 20n";
}
else{
# if condition is false then print the following
printf "a is greater than 20n";
}
print "value of a is : $an";
$a = "";
# check the boolean condition using if statement
if( $a ){
# if condition is true then print the following
printf "a has a true valuen";
}
else{
# if condition is false then print the following
printf "a has a false valuen";
}
OUTPUT
a is greater than 20
value of a is : 100
a has a false value
value of a is :
29
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(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
}
30
OUTPUT
a has a value which is 100
PROGRAM
#!/usr/local/bin/perl
$a = 100;
# check the boolean condition using if statement
if( $a == 20 ){
# if condition is true then print the following
printf "a has a value which is 20n";
}elsif( $a == 30 ){
# if condition is true then print the following
printf "a has a value which is 30n";
}else{
# if none of the above conditions is true
printf "a has a value which is $an";
}
Explanation:
 Here we are using the
equality operator == which is
used to check if two
operands are equal or not.
 If both the operands are
same, then it returns true
otherwise it retruns false.
31
 If the boolean expression evaluates to false, then the block of code inside the
unless statement will be executed.
 If boolean expression evaluates to true then the first set of code after the end of
the unless statement (after the closing curly brace) will be executed.
unless(boolean_expression)
{
# statement(s) will execute if the given condition is false
}
32
OUTPUT
a is not less than 20
value of a is : 20
a has a false value
value of a is :
Explanation:
 First unless statement makes
use of less than operator (<),
which compares two
operands and if first operand
is less than the second one
then it returns true otherwise
it returns false.
PROGRAM
#!/usr/local/bin/perl
$a = 20;
# check the boolean condition using unless
statement
unless( $a < 20 ){
# if condition is false then print the following
printf "a is not less than 20n";
}
print "value of a is : $an";
$a = "";
# check the boolean condition using unless
statement
unless ( $a ){
# if condition is false then print the following
printf "a has a false valuen";
}
print "value of a is : $an";
33
 The number 0, the strings '0' and "" , the empty list () , and undef are
all falsein a boolean context and all other values are true. Negation of
a true value by ! or not returns a special false value.
unless(boolean_expression){
# statement(s) will execute if the given condition is false
}
else{
# statement(s) will execute if the given condition is true
}
34
OUTPUT
given condition is false
value of a is : 100
a has a false value
value of a is :
PROGRAM
#!/usr/local/bin/perl
$a = 100;
# check the boolean condition using unless statement
unless( $a == 20 ){
# if condition is false then print the following
printf "given condition is falsen";
}else{
# if condition is true then print the following
printf "given condition is truen";
}
print "value of a is : $an“;
$a = "";
# check the boolean condition using unless statement
unless( $a ){
# if condition is false then print the following
printf "a has a false valuen";
}else{
# if condition is true then print the following
printf "a has a true valuen";
}
print "value of a is : $an";
printf "a has a false valuen";
}
print "value of a is : $an“;
35
When using unless , elsif , else statements there are few points to keep in mind.
 An unless can have zero or one else's and it must come after any elsif's.
 An unless 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.
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
}
36
OUTPUT
a has a value which is not 20
Explanation:
 Here we are using the
equality operator == which is
used to check if two
operands are equal or not. If
both the operands are same
then it returns true, otherwise
it retruns false.
PROGRAM
#!/usr/local/bin/perl
$a = 20;
# check the boolean condition using if statement
unless( $a == 30 ){
# if condition is false then print the following
printf "a has a value which is not 20n";
}elsif( $a == 30 ){
# if condition is true then print the following
printf "a has a value which is 30n";
}else{
# if none of the above conditions is met
printf "a has a value which is $an";
}
37
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" }
}
38
OUTPUT
number 100
number in list
PROGRAM
#!/usr/local/bin/perl
use Switch;
$var = 10;
@array = (10, 20, 30);
%hash = ('key1' => 10, 'key2' => 20);
switch($var){
case 10 { print "number 100n"; next; }
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" }
}
39
40
INTRODUCTION :
 There may be a situation when you need to execute a block of code several
number of times. In general, statements are executed sequentially: The first
statement in a function is executed first, followed by the second, and so on.
 Programming languages provide various control structures that allow for
more complicated execution paths.
41
Loop Type Description
while loop Repeats a statement or group of statements while a
given condition is true. It tests the condition before
executing the loop body.
until loop Repeats a statement or group of statements until a
given condition becomes true. It tests the condition
before executing the loop body.
for loop Executes a sequence of statements multiple times and
abbreviates the code that manages the loop variable.
foreach loop The for each loop iterates over a normal list value and
sets the variable VAR to be each element of the list in
turn.
do...while loop Like a while statement, except that it tests the condition
at the end of the loop body.
nested loops You can use one or more loop inside any another while,
for or do..while loop.
42
while(condition)
{
statement(s);
}
 The number 0, the strings '0' and "" , the empty list () , and undef are
all falsein a boolean context and all other values are true. Negation
of a true value by ! or not returns a special false value.
43
Explanation:
 Here we are using the comparison
operator < to compare value of
variable $a against 20. So while
value of $a is less than 20, while
loop continues executing a block of
code next to it and as soon as the
value of $a becomes equal to 20, it
comes out.
PROGRAM
#!/usr/local/bin/perl
$a = 10;
# while loop execution
while( $a < 20 ){
printf "Value of a: $an";
$a = $a + 1;
}
OUTPUT
Value of a: 10
Value of a: 11
Value of a: 12
Value of a: 13
Value of a: 14
Value of a: 15
Value of a: 16
Value of a: 17
Value of a: 18
Value of a: 19
44
until(condition)
{
statement(s);
}
 The number 0, the strings '0' and "" , the empty list () , and undef are
all falsein a boolean context and all other values are true. Negation
of a true value by ! or not returns a special false value.
45
Explanation:
 Here we are using the comparison
operator > to compare value of
variable $a against 10. So until the
value of $a is less than 10, until loop
continues executing a block of code
next to it and as soon as the value of
$a becomes greater than 10, it
comes out.
OUTPUT
Value of a: 5
Value of a: 6
Value of a: 7
Value of a: 8
Value of a: 9
Value of a: 10
PROGRAM
#!/usr/local/bin/perl
$a = 5;
# until loop execution
until( $a > 10 ){
printf "Value of a: $an";
$a = $a + 1;
}
46
for ( init; condition; increment )
{
statement(s);
}
Here is the flow of control in a for loop −
 The init step is executed first, and only once.
This step allows you to declare and initialize any
loop control variables. You are not required to
put a statement here, as long as a semicolon
appears.
 Next, the condition is evaluated. If it is true, the
body of the loop is executed. If it is false, the
body of the loop does not execute and flow of
control jumps to the next statement just after the
for loop.
 After the body of the for loop executes, the flow
of control jumps back up to
theincrement statement. This statement allows
you to update any loop control variables. This
statement can be left blank, as long as a
semicolon appears after the condition.
 The condition is now evaluated again. If it is true,
the loop executes and the process repeats itself
(body of loop, then increment step, and then
again condition). After the condition becomes
false, the for loop terminates.
47
OUTPUT
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19
PROGRAM
#!/usr/local/bin/perl
# for loop execution
for( $a = 10; $a < 20; $a = $a
+ 1 ){
print "value of a: $an";
}
48
foreach var (list)
{
.................
}
49
PROGRAM
#!/usr/local/bin/perl
@list = (2, 20, 30, 40, 50);
# foreach loop execution
foreach $a (@list){
print "value of a: $an";
}
OUTPUT
value of a: 2
value of a: 20
value of a: 30
value of a: 40
value of a: 50
50
do {
statement(s);
}while( condition );
 The number 0, the strings '0' and "" , the empty list () , and undef are
all falsein a boolean context and all other values are true. Negation of
a true value by ! or not returns a special false value.
51
OUTPUT
Value of a: 10
Value of a: 11
Value of a: 12
Value of a: 13
Value of a: 14
Value of a: 15
Value of a: 16
Value of a: 17
Value of a: 18
Value of a: 19
PROGRAM
#!/usr/local/bin/perl
@list = (2, 20, 30, 40, 50);
# fo#!/usr/local/bin/perl
$a = 10;
# do...while loop execution
do{
printf "Value of a: $an";
$a = $a + 1;
}while( $a < 20 );
reach loop execution
foreach $a (@list){
print "value of a: $an";
}
52
for ( init; condition; increment ){
for ( init; condition; increment ){
statement(s);
}
statement(s);
}
while(condition){
while(condition){
statement(s);
}
statement(s);
}
do{
statement(s);
do{
statement(s);
}while( condition );
}while( condition );
until(condition){
until(condition){
statement(s);
}
statement(s);
}
foreach $a (@listA){
foreach $b (@listB){
statement(s);
}
statement(s);
}
53
PROGRAM
foreach $a (@listA){
foreach $b (@listB){
statement(s);
}
statement(s); #/usr/local/bin/perl
$a = 0;
$b = 0;
# outer while loop
while($a < 3){
$b = 0;
# inner while loop
while( $b < 3 ){
print "value of a = $a, b = $bn";
$b = $b + 1;
}
$a = $a + 1;
print "Value of a = $ann";
}
}
OUTPUT
value of a = 0, b = 0
value of a = 0, b = 1
value of a = 0, b = 2
Value of a = 1
value of a = 1, b = 0
value of a = 1, b = 1
value of a = 1, b = 2
Value of a = 2
value of a = 2, b = 0
value of a = 2, b = 1
value of a = 2, b = 2
Value of a = 3
54
Control Statement Description
next statement Causes the loop to skip the remainder of its
body and immediately retest its condition prior
to reiterating.
last statement Terminates the loop statement and transfers
execution to the statement immediately
following the loop.
continue statement A continue BLOCK, it is always executed just
before the conditional is about to be evaluated
again.
redo statement The redo command restarts the loop block
without evaluating the conditional again. The
continue block, if any, is not executed.
goto statement Perl supports a goto command with three
forms: goto label, goto expr, and goto &name. 55
56
Simple answer can be given using the expression 4 + 5 is equal
to 9. Here 4 and 5 are called operands and + is called operator. Perl
language supports many operator types
 Arithmetic Operators
 Equality Operators
 Logical Operators
 Assignment Operators
 Bitwise Operators
 Logical Operators
 Quote-like Operators
 Miscellaneous Operators 57
Operator Description Example
+ Addition - Adds values on either side of
the operator
$a + $b will give 30
- Subtraction - Subtracts right hand
operand from left hand operand
$a - $b will give -10
* Multiplication - Multiplies values on
either side of the operator
$a * $b will give 200
/ Division - Divides left hand operand by
right hand operand
$b / $a will give 2
% Modulus - Divides left hand operand by
right hand operand and returns
remainder
$b % $a will give 0
** Exponent - Performs exponential
(power) calculation on operators
$a**$b will give 10 to
the power 20
58
59
60
61
62
63
64
left - terms and list operators (leftward)
left - ->
nonassoc - ++ --
right - **
right - ! ~  and unary + and -
left - =~ !~
left - * / % x
left - + - .
left - << >>
nonassoc - named unary operators
nonassoc - < > <= >= lt gt le ge
nonassoc - == != <=> eq ne cmp ~~
left - &
left - | ^
left - &&
left - || //
nonassoc - .. ...
right - ?:
right - = += -= *= etc.
left - , =>
nonassoc - list operators (rightward)
right - not
left - and
left - or xor 65
66
 Current Date & Time
 GMT Time
 Format Date & Time
 Epoch time
 POSIX Function strftime()
67
 Let's start with localtime() function, which returns values for the current date
and time if given no arguments. Following is the 9-element list returned by
the localtime function
Variables:
sec, # seconds of minutes from 0 to 61
min, # minutes of hour from 0 to 59
hour, # hours of day from 0 to 24
mday, # day of month from 1 to 31
mon, # month of year from 0 to 11
year, # year since 1900
wday, # days since sunday
yday, # days since January 1st
isdst # hours of daylight savings time
Program 1:
#!/usr/local/bin/perl
@months = qw( Jan Feb Mar Apr May Jun Jul Aug
Sep Oct Nov Dec );
@days = qw(Sun Mon Tue Wed Thu Fri Sat Sun);
($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$is
dst) = localtime();
print "$mday $months[$mon] $days[$wday]n";
Program 1:
#!/usr/local/bin/perl
$datestring = localtime();
print "Local date and time $datestringn";
Output 1:
16 Feb Sat
Output 2:
Local date and time Sat Feb 16 06:50:45 2013
68
 The function gmtime() works just like localtime() function but the returned values are
localized for the standard Greenwich time zone. When called in list context, $isdst, the
last value returned by gmtime, is always 0 . There is no Daylight Saving Time in GMT.
 You should make a note on the fact that localtime() will return the current local time on
the machine that runs the script and gmtime() will return the universal Greenwich
Mean Time, or GMT (or UTC).
PROGRAM
#!/usr/local/bin/perl
$datestring = gmtime();
print "GMT date and time $datestringn";
OUTPUT
GMT date and time Sat Feb 16 13:50:45 2013
69
 You can use localtime() function to get a list of 9-elements and later you
can use the printf()function to format date and time based on your
requirements
OUTPUT
Time Format - HH:MM:SS
06:58:52
PROGRAM
#!/usr/local/bin/perl
($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime();
printf("Time Format - HH:MM:SSn");
printf("%02d:%02d:%02d", $hour, $min, $sec);
70
 You can use the time() function to get epoch time, i.e. the numbers of
seconds that have elapsed since a given date, in Unix is January 1, 1970.
PROGRAM
#!/usr/local/bin/perl
$epoc = time();
print "Number of seconds since Jan 1, 1970 - $epocn";
OUTPUT
Number of seconds since Jan 1, 1970 - 1361022130
71
 You can use the POSIX function strftime() to format date and time with the
help of the following table. Please note that the specifiers marked with an
asterisk (*) are locale-dependent.
72
73
74
 Define and Call a Subroutine
 Passing Arguments to a Subroutine
 Passing Lists to Subroutines
 Passing Hashes to Subroutines
 Returning Value from a Subroutine
 Private Variables in a Subroutine
 Temporary Values via local()
 State Variables via state()
 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 usually is so each function performs a specific task.
75
sub subroutine_name
{
body of the subroutine
}
PROGRAM
#!/usr/bin/perl
# Function definition
sub Hello{
print "Hello, World!n";
}
# Function call
Hello();
OUTPUT
Hello, World!
The general form of a subroutine definition in Perl programming language
76
 You can pass various arguments to a subroutine like you do in any other
programming language and they can be acessed inside the function using the special
array @_. Thus the first argument to the function is in $_[0], the second is in $_[1],
and so on.
 You can pass arrays and hashes as arguments like any scalar but passing more than
one array or hash normally causes them to lose their separate identities. So we will
use references ( explained in the next chapter ) to pass any array or hash.
PROGRAM
#!/usr/bin/perl
# Function definition
sub Average{
# get total number of arguments passed.
$n = scalar(@_);
$sum = 0;
foreach $item (@_){
$sum += $item;
}
$average = $sum / $n;
print "Average for the given numbers : $averagen";
}
# Function call
Average(10, 20, 30);
OUTPUT
Average for the given numbers : 20
77
 Because the @_ variable is an array, it can be used to supply lists to a
subroutine. However, because of the way in which Perl accepts and parses
lists and arrays, it can be difficult to extract the individual elements from @_.
If you have to pass a list along with other scalar arguments, then make list as
the last argument
PROGRAM
#!/usr/bin/perl
# Function definition
sub PrintList{
my @list = @_;
print "Given list is @listn";
}
$a = 10;
@b = (1, 2, 3, 4);
# Function call with list parameter
PrintList($a, @b);
OUTPUT
Given list is 10 1 2 3 4
78
 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.
PROGRAM
#!/usr/bin/perl
# Function definition
sub PrintHash{
my (%hash) = @_;
foreach my $key ( keys %hash ){
my $value = $hash{$key};
print "$key : $valuen";
}
}
%hash = ('name' => 'Tom', 'age' => 19);
# Function call with hash parameter
PrintHash(%hash);
OUTPUT
name : Tom
age : 19
79
 You can return a value from subroutine like you do in any other programming
language. If you are not returning a value from a subroutine then whatever calculation
is last performed in a subroutine is automatically also the return value.
 You can return arrays and hashes from the subroutine like any scalar but returning
more than one array or hash normally causes them to lose their separate identities. So
we will use references ( explained in the next chapter ) to return any array or hash
from a function.
PROGRAM
#!/usr/bin/perl
# Function definition
sub Average{
# get total number of arguments passed.
$n = scalar(@_);
$sum = 0;
foreach $item (@_){
$sum += $item;
}
$average = $sum / $n;
return $average;
}
# Function call
$num = Average(10, 20, 30);
print "Average for the given numbers :
$numn";
OUTPUT
Average for the given numbers : 20
80
 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.
sub somefunc {
my $variable;
# $variable is invisible outside somefunc()
my ($another, @an_array, %a_hash);
# declaring many variables at once
}
PROGRAM
#!/usr/bin/perl
# Global variable
$string = "Hello, World!";
# Function definition
sub PrintHello{
# Private variable for PrintHello
function
my $string;
$string = "Hello, Perl!";
print "Inside the function $stringn";
}
# Function call
PrintHello();
print "Outside the function $stringn";
OUTPUT
Inside the function Hello, Perl!
Outside the function Hello, World!
81
 The local is mostly used when the current value of a variable must be visible
to called subroutines. A local just gives temporary values to global (meaning
package) variables. This is known as dynamic scoping. Lexical scoping is
done with my, which works more like C's auto declarations.
#!/usr/bin/perl
# Global variable
$string = "Hello, World!";
sub PrintHello{
# Private variable for Print Hello function
local $string;
$string = "Hello, Perl!";
PrintMe();
print "Inside the function Print Hello $stringn";
}
sub PrintMe{
print "Inside the function PrintMe $stringn";
}
# Function call
PrintHello();
print "Outside the function $stringn";
OUTPUT
Inside the function PrintMe Hello, Perl!
Inside the function PrintHello Hello, Perl!
Outside the function Hello, World!
82
 There are another type of lexical variables, which are similar to private variables but
they maintain their state and they do not get reinitialized upon multiple calls of the
subroutines. These variables are defined using the state operator and available
starting from Perl
PROGRAM
#!/usr/bin/perl
use feature 'state';
sub PrintCount{
state $count = 0; # initial value
print "Value of counter is $countn";
$count++;
}
for (1..5){
PrintCount();
}
OUTPUT
Value of counter is 0
Value of counter is 1
Value of counter is 2
Value of counter is 3
Value of counter is 4
83
84
 A Perl reference is a scalar data type that holds the location of another value
which could be scalar, arrays, or hashes. Because of its scalar nature, a
reference can be used anywhere, a scalar can be used.
 Create References
 Dereferencing
 Circular References
 References to Functions
85
 It is easy to create a reference for any variable, subroutine or value by
prefixing it with a backslash.
$scalarref = $foo;
$arrayref = @ARGV;
$hashref = %ENV;
$coderef = &handler;
$globref = *foo;
 You cannot create a reference on an I/O handle (filehandle or dirhandle) using the
backslash operator but a reference to an anonymous array can be created using the
square brackets.
$arrayref = [1, 2, ['a', 'b', 'c']];
 Similar way you can create a reference to an anonymous hash using the curly brackets.
$hashref = {
'Adam' => 'Eve',
'Clyde' => 'Bonnie',
}; 86
PROGRAM
#!/usr/bin/perl
$var = 10;
$r = $var;
print "Reference type in r : ", ref($r), "n";
@var = (1, 2, 3);
$r = @var;
print "Reference type in r : ", ref($r), "n";
%var = ('key1' => 10, 'key2' => 20);
$r = %var;
print "Reference type in r : ", ref($r), "n";
 Dereferencing returns the value from a reference point to the location. To dereference
a reference simply use $, @ or % as prefix of the reference variable depending on
whether the reference is pointing to a scalar, array, or hash.
OUTPUT
Reference type in r : SCALAR
Reference type in r : ARRAY
Reference type in r : HASH
87
 A circular reference occurs when two references contain a reference to each other.
You have to be careful while creating references otherwise a circular reference can
lead to memory leaks.
PROGRAM
#!/usr/bin/perl
my $foo = 100;
$foo = $foo;
print "Value of foo is : ", $$foo, "n";
OUTPUT
Value of foo is : REF(0x9aae38)
88
 This might happen if you need to create a signal handler so you can produce a
reference to a function by preceding that function name with & and to dereference that
reference you simply need to prefix reference variable using ampersand &.
PROGRAM
#!/usr/bin/perl
# Function definition
sub PrintHash{
my (%hash) = @_;
foreach $item (%hash){
print "Item : $itemn";
}
}
%hash = ('name' => 'Tom', 'age' => 19);
# Create a reference to above function.
$cref = &PrintHash;
# Function call using reference.
&$cref(%hash);
OUTPUT
Item : name
Item : Tom
Item : age
Item : 19
89
90
 Perl uses a writing template called a 'format' to output reports. To use the format
feature of Perl, you have to define a format first and then you can use that format to
write formatted data.
91
 Define a Format
 Using the Format
 Define a Report Header
 Define a Pagination
 Perl - Special Variables
92
format FormatName =
fieldline
value_one, value_two, value_three
fieldline
value_one, value_two
 Here FormatName represents the name of the format. The fieldline is the specific
way, the data should be formatted. The values lines represent the values that will be
entered into the field line. You end the format with a single period.
 Next fieldline can contain any text or fieldholders. The fieldholders hold space for
data that will be placed there at a later date.
PROGRAM
format EMPLOYEE =
===================================
@<<<<<<<<<<<<<<<<<<<<<< @<<
$name $age
@#####.##
$salary
===================================
EXPLANATION
 In this example, $name would be written as left justify within 22 character
spaces and after that age will be written in two spaces.
93
 In order to invoke this format declaration, we would use the write keyword −
write EMPLOYEE;
 The problem is that the format name is usually the name of an open file handle, and
the write statement will send the output to this file handle. As we want the data sent to
the STDOUT, we must associate EMPLOYEE with the STDOUT file handle. First,
however, we must make sure that that STDOUT is our selected file handle, using the
select() function.
select(STDOUT);
 We would then associate EMPLOYEE with STDOUT by setting the new format name
with STDOUT, using the special variable $~ or $FORMAT_NAME as follows −
$~ = "EMPLOYEE";
 When we now do a write(), the data would be sent to STDOUT. Remember: if
you are going to write your report in any other file handle instead of STDOUT
then you can use select() function to select that file handle and rest of the
logic will remain the same.
94
 Let's take the following example. Here we have hard coded values just for showing the
usage. In actual usage you will read values from a file or database to generate actual
reports and you may need to write final report again into a file.
PROGRAM
#!/usr/bin/perl
format EMPLOYEE =
=======================
@<<<<<<<<<<<<<<<<<<<<<< @<<
$name $age
@#####.##
$salary
======================
.
select(STDOUT);
$~ = EMPLOYEE;
@n = ("Ali", "Raza", "Jaffer");
@a = (20,30, 40);
@s = (2000.00, 2500.00, 4000.000);
$i = 0;
foreach (@n){
$name = $_;
$age = $a[$i];
$salary = $s[$i++];
write;
}
OUTPUT
=========================
Ali 20
2000.00
=========================
=========================
Raza 30
2500.00
=========================
=========================
Jaffer 40
4000.00
=========================
95
 Everything looks fine. But you would be interested in adding a header to your report.
This header will be printed on top of each page. It is very simple to do this. Apart from
defining a template you would have to define a header and assign it to $^ or
$FORMAT_TOP_NAME variable.
PROGRAM
#!/usr/bin/perl
format EMPLOYEE =
========================
@<<<<<<<<<<<<<<<<<<<<<< @<<
$name $age
@#####.##
$salary
========================
.
format EMPLOYEE_TOP =
========================
Name Age
========================
.
select(STDOUT);
$~ = EMPLOYEE;
$^ = EMPLOYEE_TOP;
@n = ("Ali", "Raza", "Jaffer");
@a = (20,30, 40);
@s = (2000.00, 2500.00, 4000.000);
$i = 0;
foreach (@n){
$name = $_;
$age = $a[$i];
$salary = $s[$i++];
write;
}
OUTPUT
=====================
Name Age
=====================
=====================
Ali 20
2000.00
=====================
=====================
Raza 30
2500.00
=====================
=====================
Jaffer 40
4000.00
=====================
96
 What about if your report is taking more than one page? You have a solution
for that, simply use $% or $FORMAT_PAGE_NUMBER vairable along with
header.
PROGRAM
format EMPLOYEE_TOP =
=======================
Name Age Page @<
$%
=======================
.
OUTPUT
======================
Name Age Page 1
======================
======================
Ali 20
2000.00
======================
======================
Raza 30
2500.00
======================
======================
Jaffer 40
4000.00
======================
HINT
 You can set the number of
lines per page using special
variable $= ( or
$FORMAT_LINES_PER_PAG
E ), By default $= will be 60.
97
98
 The basics of handling files are simple: you associate a filehandle with an
external entity (usually a file) and then use a variety of operators and
functions within Perl to read and update the data stored within the data
stream associated with the filehandle.
 Opening and Closing Files
 Open Function
 Sysopen Function
 Close Function
 Reading and Writing Files
99
 There are following two functions with multiple forms, which can be used to
open any new or existing file in Perl.
open FILEHANDLE, EXPR
open FILEHANDLE
sysopen FILEHANDLE, FILENAME,
MODE, PERMS
sysopen FILEHANDLE, FILENAME,
MODE
 Here FILEHANDLE is the file handle returned by the open function and
EXPR is the expression having file name and mode of opening the file.
100
 Following is the syntax to open file.txt in read-only mode. Here less than < sign
indicates that file has to be opend in read-only mode.
open(DATA, "<file.txt");
 Here DATA is the file handle which will be used to read the file. Here is the example
which will open a file and will print its content over the screen.
#!/usr/bin/perl
open(DATA, "<file.txt") or die "Couldn't open file file.txt, $!“;
while(<DATA>){
print "$_";
}
 Following is the syntax to open file.txt in writing mode. Here less than > sign indicates
that file has to be opend in the writing mode.
open(DATA, ">file.txt") or die "Couldn't open file file.txt, $!";
101
 For example, to open a file for updating without truncating it −
open(DATA, "+<file.txt"); or die "Couldn't open file file.txt, $!";
 To truncate the file first −
open DATA, "+>file.txt" or die "Couldn't open file file.txt, $!";
 You can open a file in the append mode. In this mode writing point will be set to
the end of the file.
open(DATA,">>file.txt") || die "Couldn't open file file.txt, $!";
 A double >> opens the file for appending, placing the file pointer at the end, so
that you can immediately start appending information. However, you can't read
from it unless you also place a plus sign in front of it −
open(DATA,"+>>file.txt") || die "Couldn't open file file.txt, $!";
102
 The sysopen function is similar to the main open function, except that it uses the
systemopen() function, using the parameters supplied to it as the parameters for the
system function.
sysopen(DATA, "file.txt", O_RDWR);
 truncate the file before updating
sysopen(DATA, "file.txt", O_RDWR|O_TRUNC );
 The PERMS argument specifies the file permissions for the file specified if it has to be
created. By default it takes 0x666.
103
 To close a filehandle, and therefore disassociate the filehandle from the corresponding
file, you use the close function. This flushes the filehandle's buffers and closes the
system's file descriptor.
close FILEHANDLE
close
 If no FILEHANDLE is specified, then it closes the currently selected filehandle. It
returns true only if it could successfully flush the buffers and close the file.
close(DATA) || die "Couldn't close file properly";
104
 Once you have an open file handle, you need to be able to read and write
information. There are a number of different ways of reading and writing data
into the file.
 getc Function
 read Function
 print Function
 Copying Files
105
 The getc function returns a single character from the specified
FILEHANDLE, or STDIN if none is specified
getc FILEHANDLE
getc
 The read function reads a block of information from the buffered filehandle:
This function is used to read binary data from the file.
read FILEHANDLE, SCALAR, LENGTH, OFFSET
read FILEHANDLE, SCALAR, LENGTH
 The print function prints the evaluated value of LIST to FILEHANDLE, or to
the current output file handle (STDOUT by default).
print "Hello World!n";
106
 Here is the example, which opens an existing file file1.txt and read it line by
line and generate another copy file file2.txt.
#!/usr/bin/perl
# Open file to read
open(DATA1, "<file1.txt");
# Open new file to write
open(DATA2, ">file2.txt");
# Copy data fro
107
108
 Most of the special variables have an english like long name, e.g., Operating
System Error variable $! can be written as $OS_ERROR. But if you are
going to use english like names, then you would have to put one line use
English; at the top of your program file. This guides the interpreter to pickup
exact meaning of the variable.
 Global Scalar Special Variables.
 Global Array Special Variables.
 Global Hash Special Variables.
 Global Special File handles.
 Global Special Constants.
 Regular Expression Special Variables.
 File handle Special Variables.
109
110
111
112
Symbol Description
@ARGV
The array containing the command-line arguments
intended for the script.
@INC
The array containing the list of places to look for
Perl scripts to be evaluated by the do, require, or
use constructs.
@F
The array into which the input lines are split when
the -a command-line switch is given.
113
Symbol Description
%INC The hash containing entries for the filename of
each file that has been included via do or require.
%ENV The hash containing your current environment.
%SIG
The hash used to set signal handlers for various
signals.
114
Symbol Description
ARGV The special filehandle that iterates over command line
filenames in @ARGV. Usually written as the null filehandle
in <>.
STDERR The special filehandle for standard error in any package.
STDIN The special filehandle for standard input in any package.
STDOUT The special filehandle for standard output in any package.
DATA The special filehandle that refers to anything following the
__END__ token in the file containing the script. Or, the
special filehandle for anything following the __DATA__
token in a required file, as long as you're reading data in
the same package __DATA__ was found in.
_ (underscore) The special filehandle used to cache the information from
the last stat, lstat, or file test operator.
115
Symbol Description
__END__
Indicates the logical end of your program. Any
following text is ignored, but may be read via the
DATA filehandle.
__FILE__
Represents the filename at the point in your
program where it's used. Not interpolated into
strings.
__LINE__
Represents the current line number. Not
interpolated into strings.
__PACKAGE__
Represents the current package name at
compile time, or undefined if there is no current
package. Not interpolated into strings.
116
Symbol Description
$digit
Contains the text matched by the
corresponding set of parentheses in the last
pattern matched. For example, $1 matches
whatever was contained in the first set of
parentheses in the previous regular
expression.
$&, $MATCH The string matched by the last successful
pattern match.
$`, $PREMATCH The string preceding whatever was matched
by the last successful pattern match.
$‘, $POSTMATCH The string following whatever was matched by
the last successful pattern match.
$+,
$LAST_PAREN_MATCH
The last bracket matched by the last search
pattern. This is useful if you don't know which
of a set of alternative patterns was matched.
For example: /Version: (.*)|Revision: (.*)/ &&
($rev = $+);
117
118
119
 Perl - Socket Programming
 Perl – Object Oriented
 Perl – Database Access
 Perl – CGI Programming
 Perl – Packages and Modules
 Perl – Process Management
 Perl – Embedded Documentation
120
 Socket is a Berkeley UNIX mechanism of creating a virtual duplex
connection between different processes. This was later ported on to every
known OS enabling communication between systems across geographical
location running on different OS software. If not for the socket, most of the
network communication between systems would never ever have happened.
 To Create a Server
 To Create a Client
 Server Side Socket Calls
 The bind() call
 The listen() call
 The accept() call
 Client Side Socket Calls
 The connect() call
121
 We have already studied references in Perl and Perl anonymous arrays and
hashes. Object Oriented concept in Perl is very much based on references
and anonymous array and hashes. Let's start learning basic concepts of
Object Oriented Perl.
 Object Basics
 Defining a Class
 Creating and Using Objects
 Defining Methods
 Inheritance
 Method Overriding
 Default Auto loading
 Destructors and Garbage Collection
122
 DBI stands for Database Independent Interface for Perl, which means DBI
provides an abstraction layer between the Perl code and the underlying
database, allowing you to switch database implementations really easily.
 The DBI is a database access module for the Perl programming language. It
provides a set of methods, variables, and conventions that provide a
consistent database interface, independent of the actual database being
used.
Architecture of DBI - Databases
123
 Notation and Conventions
 Database Connection
 INSERT Operation
 Using Bind Values
 READ Operation
 UPDATE Operation
 DELETE Operation
 COMMIT Operation
 ROLLBACK Operation
 Begin Transaction
 Auto Commit Option
 Automatic Error Handling
 Disconnecting Database
 Using NULL Values
 Some Other DBI Functions
124
 A Common Gateway Interface, or CGI, is a set of standards that defines
how information is exchanged between the web server and a custom script.
 The CGI specifications are currently maintained by the NCSA and NCSA
defines CGI is as follows −
 The Common Gateway Interface, or CGI, is a standard for external gateway
programs to interface with information servers such as HTTP servers.
 The current version is CGI/1.1 and CGI/1.2 is under progress.
Architecture of CGI Programming
125
 First CGI Program
 Understanding HTTP Header
 CGI Environment Variables
 Raise a "File Download" Dialog Box?
 GET and POST Methods
 Passing Information using GET Method
 Simple URL Example: Get Method
 Simple FORM Example: GET Method
 Passing Information using POST Method
 Passing Checkbox Data to CGI Program
 Passing Radio Button Data to CGI Program
 Passing Text Area Data to CGI Program
 Passing Drop Down Box Data to CGI Program
 Using Cookies in CGI
 CGI Modules and Libraries
126
 A package is a collection of code which lives in its own namespace.
 A namespace is a named collection of unique variable names (also called a
symbol table).
 Namespaces prevent variable name collisions between packages.
 Packages enable the construction of modules which, when used, won't
clobber variables and functions outside of the modules's own namespace.
 The package stays in effect until either another package statement is invoked,
or until the end of the current block or file.
 You can explicitly refer to variables within a package using the :: package
qualifier.
 BEGIN and END Blocks
 What are Perl Modules?
 The Require Function
 The Use Function
 Create the Perl Module Tree
 Installing Perl Module
127
You can use Perl in various ways to create new processes as per your requirements. This
tutorial will list down few important and most frequently used methods of creating and
managing Perl processes.
 You can use special variables $$ or $PROCESS_ID to get current process ID.
 Every process created using any of the mentioned methods, maintains its own virtual
environment with-in %ENV variable.
 The exit() function always exits just the child process which executes this function and
the main process as a whole will not exit unless all running child-processes have exited.
 All open handles are dup()-ed in child-processes, so that closing any handles in one
process does not affect the others.
 Backstick Operator
 The system() Function
 The fork() Function
 The kill() Function
128
 You can embed Pod (Plain Old Text) documentation in your Perl modules and scripts.
Following is the rule to use embedded documentation in your Perl Code.
What is POD?
 Pod is a simple-to-use markup language used for writing documentation for Perl, Perl
programs, and Perl modules. There are various translators available for converting Pod
to various formats like plain text, HTML, man pages, and more. Pod markup consists of
three basic kinds of paragraphs −
 Ordinary Paragraph: You can use formatting codes in ordinary paragraphs, for
bold, italic, code-style , hyperlinks, and more.
 Verbatim Paragraph: Verbatim paragraphs are usually used for presenting a
codeblock or other text which does not require any special parsing or formatting,
and which shouldn't be wrapped.
 Command Paragraph: A command paragraph is used for special treatment of
whole chunks of text, usually as headings or parts of lists. All command
paragraphs start with =, followed by an identifier, followed by arbitrary text that
the command can use however it pleases. Currently recognized commands.
129
Ad

More Related Content

What's hot (18)

perl course-in-mumbai
 perl course-in-mumbai perl course-in-mumbai
perl course-in-mumbai
vibrantuser
 
Bottom up parser
Bottom up parserBottom up parser
Bottom up parser
Akshaya Arunan
 
Data types in php
Data types in phpData types in php
Data types in php
ilakkiya
 
Php intro by sami kz
Php intro by sami kzPhp intro by sami kz
Php intro by sami kz
sami2244
 
Top down and botttom up Parsing
Top down     and botttom up ParsingTop down     and botttom up Parsing
Top down and botttom up Parsing
Gerwin Ocsena
 
Operator precedence
Operator precedenceOperator precedence
Operator precedence
Akshaya Arunan
 
Lecture 2 php basics (1)
Lecture 2  php basics (1)Lecture 2  php basics (1)
Lecture 2 php basics (1)
Core Lee
 
PHP Reviewer
PHP ReviewerPHP Reviewer
PHP Reviewer
Cecilia Pamfilo
 
Perl intro
Perl introPerl intro
Perl intro
Kanchilug
 
03phpbldgblock
03phpbldgblock03phpbldgblock
03phpbldgblock
IIUM
 
Advanced perl finer points ,pack&amp;unpack,eval,files
Advanced perl   finer points ,pack&amp;unpack,eval,filesAdvanced perl   finer points ,pack&amp;unpack,eval,files
Advanced perl finer points ,pack&amp;unpack,eval,files
Shankar D
 
Module 11
Module 11Module 11
Module 11
bittudavis
 
Php String And Regular Expressions
Php String  And Regular ExpressionsPhp String  And Regular Expressions
Php String And Regular Expressions
mussawir20
 
LR parsing
LR parsingLR parsing
LR parsing
ichikaz3
 
Php2
Php2Php2
Php2
Keennary Pungyera
 
Operator precedance parsing
Operator precedance parsingOperator precedance parsing
Operator precedance parsing
sanchi29
 
Lecture 23
Lecture 23Lecture 23
Lecture 23
rhshriva
 
Left factor put
Left factor putLeft factor put
Left factor put
siet_pradeep18
 
perl course-in-mumbai
 perl course-in-mumbai perl course-in-mumbai
perl course-in-mumbai
vibrantuser
 
Data types in php
Data types in phpData types in php
Data types in php
ilakkiya
 
Php intro by sami kz
Php intro by sami kzPhp intro by sami kz
Php intro by sami kz
sami2244
 
Top down and botttom up Parsing
Top down     and botttom up ParsingTop down     and botttom up Parsing
Top down and botttom up Parsing
Gerwin Ocsena
 
Lecture 2 php basics (1)
Lecture 2  php basics (1)Lecture 2  php basics (1)
Lecture 2 php basics (1)
Core Lee
 
03phpbldgblock
03phpbldgblock03phpbldgblock
03phpbldgblock
IIUM
 
Advanced perl finer points ,pack&amp;unpack,eval,files
Advanced perl   finer points ,pack&amp;unpack,eval,filesAdvanced perl   finer points ,pack&amp;unpack,eval,files
Advanced perl finer points ,pack&amp;unpack,eval,files
Shankar D
 
Php String And Regular Expressions
Php String  And Regular ExpressionsPhp String  And Regular Expressions
Php String And Regular Expressions
mussawir20
 
LR parsing
LR parsingLR parsing
LR parsing
ichikaz3
 
Operator precedance parsing
Operator precedance parsingOperator precedance parsing
Operator precedance parsing
sanchi29
 
Lecture 23
Lecture 23Lecture 23
Lecture 23
rhshriva
 

Similar to Complete Overview about PERL (20)

newperl5
newperl5newperl5
newperl5
tutorialsruby
 
newperl5
newperl5newperl5
newperl5
tutorialsruby
 
Perl_Part2
Perl_Part2Perl_Part2
Perl_Part2
Frank Booth
 
Introduction to perl_lists
Introduction to perl_listsIntroduction to perl_lists
Introduction to perl_lists
Vamshi Santhapuri
 
Introduction to perl scripting______.ppt
Introduction to perl scripting______.pptIntroduction to perl scripting______.ppt
Introduction to perl scripting______.ppt
nalinisamineni
 
Introduction to Perl
Introduction to PerlIntroduction to Perl
Introduction to Perl
NBACriteria2SICET
 
perltut
perltutperltut
perltut
tutorialsruby
 
perltut
perltutperltut
perltut
tutorialsruby
 
Perl Basics with Examples
Perl Basics with ExamplesPerl Basics with Examples
Perl Basics with Examples
Nithin Kumar Singani
 
Lecture19-20
Lecture19-20Lecture19-20
Lecture19-20
tutorialsruby
 
Lecture19-20
Lecture19-20Lecture19-20
Lecture19-20
tutorialsruby
 
Unit 1-perl names values and variables
Unit 1-perl names values and variablesUnit 1-perl names values and variables
Unit 1-perl names values and variables
sana mateen
 
Scala syntax analysis
Scala syntax analysisScala syntax analysis
Scala syntax analysis
Ildar Nurgaliev
 
Lecture 22
Lecture 22Lecture 22
Lecture 22
rhshriva
 
Chap1introppt2php(finally done)
Chap1introppt2php(finally done)Chap1introppt2php(finally done)
Chap1introppt2php(finally done)
monikadeshmane
 
Scalar data types
Scalar data typesScalar data types
Scalar data types
Krasimir Berov (Красимир Беров)
 
Perl programming language
Perl programming languagePerl programming language
Perl programming language
Elie Obeid
 
Introduction to perl_control structures
Introduction to perl_control structuresIntroduction to perl_control structures
Introduction to perl_control structures
Vamshi Santhapuri
 
Practical approach to perl day1
Practical approach to perl day1Practical approach to perl day1
Practical approach to perl day1
Rakesh Mukundan
 
PERL PROGRAMMING LANGUAGE Basic Introduction
PERL PROGRAMMING LANGUAGE Basic IntroductionPERL PROGRAMMING LANGUAGE Basic Introduction
PERL PROGRAMMING LANGUAGE Basic Introduction
johnboladevice
 
Ad

Recently uploaded (20)

Top 12 Most Useful AngularJS Development Tools to Use in 2025
Top 12 Most Useful AngularJS Development Tools to Use in 2025Top 12 Most Useful AngularJS Development Tools to Use in 2025
Top 12 Most Useful AngularJS Development Tools to Use in 2025
GrapesTech Solutions
 
How to Troubleshoot 9 Types of OutOfMemoryError
How to Troubleshoot 9 Types of OutOfMemoryErrorHow to Troubleshoot 9 Types of OutOfMemoryError
How to Troubleshoot 9 Types of OutOfMemoryError
Tier1 app
 
A Comprehensive Guide to CRM Software Benefits for Every Business Stage
A Comprehensive Guide to CRM Software Benefits for Every Business StageA Comprehensive Guide to CRM Software Benefits for Every Business Stage
A Comprehensive Guide to CRM Software Benefits for Every Business Stage
SynapseIndia
 
Wilcom Embroidery Studio Crack 2025 For Windows
Wilcom Embroidery Studio Crack 2025 For WindowsWilcom Embroidery Studio Crack 2025 For Windows
Wilcom Embroidery Studio Crack 2025 For Windows
Google
 
Adobe Media Encoder Crack FREE Download 2025
Adobe Media Encoder  Crack FREE Download 2025Adobe Media Encoder  Crack FREE Download 2025
Adobe Media Encoder Crack FREE Download 2025
zafranwaqar90
 
Troubleshooting JVM Outages – 3 Fortune 500 case studies
Troubleshooting JVM Outages – 3 Fortune 500 case studiesTroubleshooting JVM Outages – 3 Fortune 500 case studies
Troubleshooting JVM Outages – 3 Fortune 500 case studies
Tier1 app
 
sequencediagrams.pptx software Engineering
sequencediagrams.pptx software Engineeringsequencediagrams.pptx software Engineering
sequencediagrams.pptx software Engineering
aashrithakondapalli8
 
Programs as Values - Write code and don't get lost
Programs as Values - Write code and don't get lostPrograms as Values - Write code and don't get lost
Programs as Values - Write code and don't get lost
Pierangelo Cecchetto
 
Orion Context Broker introduction 20250509
Orion Context Broker introduction 20250509Orion Context Broker introduction 20250509
Orion Context Broker introduction 20250509
Fermin Galan
 
Top Magento Hyvä Theme Features That Make It Ideal for E-commerce.pdf
Top Magento Hyvä Theme Features That Make It Ideal for E-commerce.pdfTop Magento Hyvä Theme Features That Make It Ideal for E-commerce.pdf
Top Magento Hyvä Theme Features That Make It Ideal for E-commerce.pdf
evrigsolution
 
Surviving a Downturn Making Smarter Portfolio Decisions with OnePlan - Webina...
Surviving a Downturn Making Smarter Portfolio Decisions with OnePlan - Webina...Surviving a Downturn Making Smarter Portfolio Decisions with OnePlan - Webina...
Surviving a Downturn Making Smarter Portfolio Decisions with OnePlan - Webina...
OnePlan Solutions
 
Memory Management and Leaks in Postgres from pgext.day 2025
Memory Management and Leaks in Postgres from pgext.day 2025Memory Management and Leaks in Postgres from pgext.day 2025
Memory Management and Leaks in Postgres from pgext.day 2025
Phil Eaton
 
Sequence Diagrams With Pictures (1).pptx
Sequence Diagrams With Pictures (1).pptxSequence Diagrams With Pictures (1).pptx
Sequence Diagrams With Pictures (1).pptx
aashrithakondapalli8
 
Why Tapitag Ranks Among the Best Digital Business Card Providers
Why Tapitag Ranks Among the Best Digital Business Card ProvidersWhy Tapitag Ranks Among the Best Digital Business Card Providers
Why Tapitag Ranks Among the Best Digital Business Card Providers
Tapitag
 
Download MathType Crack Version 2025???
Download MathType Crack  Version 2025???Download MathType Crack  Version 2025???
Download MathType Crack Version 2025???
Google
 
From Vibe Coding to Vibe Testing - Complete PowerPoint Presentation
From Vibe Coding to Vibe Testing - Complete PowerPoint PresentationFrom Vibe Coding to Vibe Testing - Complete PowerPoint Presentation
From Vibe Coding to Vibe Testing - Complete PowerPoint Presentation
Shay Ginsbourg
 
Deploying & Testing Agentforce - End-to-end with Copado - Ewenb Clark
Deploying & Testing Agentforce - End-to-end with Copado - Ewenb ClarkDeploying & Testing Agentforce - End-to-end with Copado - Ewenb Clark
Deploying & Testing Agentforce - End-to-end with Copado - Ewenb Clark
Peter Caitens
 
The Elixir Developer - All Things Open
The Elixir Developer - All Things OpenThe Elixir Developer - All Things Open
The Elixir Developer - All Things Open
Carlo Gilmar Padilla Santana
 
Serato DJ Pro Crack Latest Version 2025??
Serato DJ Pro Crack Latest Version 2025??Serato DJ Pro Crack Latest Version 2025??
Serato DJ Pro Crack Latest Version 2025??
Web Designer
 
Mastering Selenium WebDriver: A Comprehensive Tutorial with Real-World Examples
Mastering Selenium WebDriver: A Comprehensive Tutorial with Real-World ExamplesMastering Selenium WebDriver: A Comprehensive Tutorial with Real-World Examples
Mastering Selenium WebDriver: A Comprehensive Tutorial with Real-World Examples
jamescantor38
 
Top 12 Most Useful AngularJS Development Tools to Use in 2025
Top 12 Most Useful AngularJS Development Tools to Use in 2025Top 12 Most Useful AngularJS Development Tools to Use in 2025
Top 12 Most Useful AngularJS Development Tools to Use in 2025
GrapesTech Solutions
 
How to Troubleshoot 9 Types of OutOfMemoryError
How to Troubleshoot 9 Types of OutOfMemoryErrorHow to Troubleshoot 9 Types of OutOfMemoryError
How to Troubleshoot 9 Types of OutOfMemoryError
Tier1 app
 
A Comprehensive Guide to CRM Software Benefits for Every Business Stage
A Comprehensive Guide to CRM Software Benefits for Every Business StageA Comprehensive Guide to CRM Software Benefits for Every Business Stage
A Comprehensive Guide to CRM Software Benefits for Every Business Stage
SynapseIndia
 
Wilcom Embroidery Studio Crack 2025 For Windows
Wilcom Embroidery Studio Crack 2025 For WindowsWilcom Embroidery Studio Crack 2025 For Windows
Wilcom Embroidery Studio Crack 2025 For Windows
Google
 
Adobe Media Encoder Crack FREE Download 2025
Adobe Media Encoder  Crack FREE Download 2025Adobe Media Encoder  Crack FREE Download 2025
Adobe Media Encoder Crack FREE Download 2025
zafranwaqar90
 
Troubleshooting JVM Outages – 3 Fortune 500 case studies
Troubleshooting JVM Outages – 3 Fortune 500 case studiesTroubleshooting JVM Outages – 3 Fortune 500 case studies
Troubleshooting JVM Outages – 3 Fortune 500 case studies
Tier1 app
 
sequencediagrams.pptx software Engineering
sequencediagrams.pptx software Engineeringsequencediagrams.pptx software Engineering
sequencediagrams.pptx software Engineering
aashrithakondapalli8
 
Programs as Values - Write code and don't get lost
Programs as Values - Write code and don't get lostPrograms as Values - Write code and don't get lost
Programs as Values - Write code and don't get lost
Pierangelo Cecchetto
 
Orion Context Broker introduction 20250509
Orion Context Broker introduction 20250509Orion Context Broker introduction 20250509
Orion Context Broker introduction 20250509
Fermin Galan
 
Top Magento Hyvä Theme Features That Make It Ideal for E-commerce.pdf
Top Magento Hyvä Theme Features That Make It Ideal for E-commerce.pdfTop Magento Hyvä Theme Features That Make It Ideal for E-commerce.pdf
Top Magento Hyvä Theme Features That Make It Ideal for E-commerce.pdf
evrigsolution
 
Surviving a Downturn Making Smarter Portfolio Decisions with OnePlan - Webina...
Surviving a Downturn Making Smarter Portfolio Decisions with OnePlan - Webina...Surviving a Downturn Making Smarter Portfolio Decisions with OnePlan - Webina...
Surviving a Downturn Making Smarter Portfolio Decisions with OnePlan - Webina...
OnePlan Solutions
 
Memory Management and Leaks in Postgres from pgext.day 2025
Memory Management and Leaks in Postgres from pgext.day 2025Memory Management and Leaks in Postgres from pgext.day 2025
Memory Management and Leaks in Postgres from pgext.day 2025
Phil Eaton
 
Sequence Diagrams With Pictures (1).pptx
Sequence Diagrams With Pictures (1).pptxSequence Diagrams With Pictures (1).pptx
Sequence Diagrams With Pictures (1).pptx
aashrithakondapalli8
 
Why Tapitag Ranks Among the Best Digital Business Card Providers
Why Tapitag Ranks Among the Best Digital Business Card ProvidersWhy Tapitag Ranks Among the Best Digital Business Card Providers
Why Tapitag Ranks Among the Best Digital Business Card Providers
Tapitag
 
Download MathType Crack Version 2025???
Download MathType Crack  Version 2025???Download MathType Crack  Version 2025???
Download MathType Crack Version 2025???
Google
 
From Vibe Coding to Vibe Testing - Complete PowerPoint Presentation
From Vibe Coding to Vibe Testing - Complete PowerPoint PresentationFrom Vibe Coding to Vibe Testing - Complete PowerPoint Presentation
From Vibe Coding to Vibe Testing - Complete PowerPoint Presentation
Shay Ginsbourg
 
Deploying & Testing Agentforce - End-to-end with Copado - Ewenb Clark
Deploying & Testing Agentforce - End-to-end with Copado - Ewenb ClarkDeploying & Testing Agentforce - End-to-end with Copado - Ewenb Clark
Deploying & Testing Agentforce - End-to-end with Copado - Ewenb Clark
Peter Caitens
 
Serato DJ Pro Crack Latest Version 2025??
Serato DJ Pro Crack Latest Version 2025??Serato DJ Pro Crack Latest Version 2025??
Serato DJ Pro Crack Latest Version 2025??
Web Designer
 
Mastering Selenium WebDriver: A Comprehensive Tutorial with Real-World Examples
Mastering Selenium WebDriver: A Comprehensive Tutorial with Real-World ExamplesMastering Selenium WebDriver: A Comprehensive Tutorial with Real-World Examples
Mastering Selenium WebDriver: A Comprehensive Tutorial with Real-World Examples
jamescantor38
 
Ad

Complete Overview about PERL

  • 2. 2
  • 3.  Perl is a stable, cross platform programming language.  It is used for mission critical projects in the public and private sectors.  Perl is an Open Source software, licensed under its Artistic License, or the GNU General Public License (GPL).  Perl was created by Larry Wall. INTRODUCTION : 3
  • 4. 4
  • 5. PERL FEATURES :  Perl takes the best features from other languages, such as C, awk, sed, sh, and BASIC, among others.  Perls database integration interface DBI supports third-party databases including Oracle, Sybase, Postgres, MySQL and others.  Perl works with HTML, XML, and other mark-up languages.  Perl supports Unicode.  Perl supports both procedural and object-oriented programming.  The Perl interpreter can be embedded into other systems. 5
  • 6. 6
  • 7. PERL INTERPRETED :  Perl is an interpreted language, which means that your code can be run as is, without a compilation stage that creates a non portable executable program.  Traditional compilers convert programs into machine language. When you run a Perl program, it's first compiled into a byte code, which is then converted ( as the program runs) into machine instructions. 7
  • 8. 8
  • 9. PERL IDENTIFIERS :  A Perl identifier is a name used to identify a variable, function, class, module, or other object.  A Perl variable name starts with either $, @ or % followed by zero or more letters, underscores, and digits (0 to 9).  Perl does not allow punctuation characters such as @, $, and % within identifiers.  Perl is a case sensitive programming language. Example:  $Manpower and $manpower are two different identifiers in Perl. 9
  • 10. 10
  • 11. S.N Types and Description 1 Scalar − Scalars are simple variables. They are preceded by a dollar sign ($). A scalar is either a number, a string, or a reference. A reference is actually an address of a variable, which we will see in the upcoming chapters. 2 Arrays − Arrays are ordered lists of scalars that you access with a numeric index which starts with 0. They are preceded by an "at" sign (@). 3 Hashes −Hashes are unordered sets of key/value pairs that you access using the keys as subscripts. They are preceded by a percent sign (%). PERL DATATYPES : 11
  • 12. STRING LITERALS & ESCAPE SEQUENCE :  Double-quoted string literals allow variable interpolation.  single-quoted string literals Doesn’t allow variable interpolation.  There are certain characters when they are proceeded by a back slash, have special meaning and they are used to represent like newline (n) or tab (t). 12
  • 13. EXAMPLE PROGRAM : #!/usr/bin/perl # This is case of interpolation. $str = "Welcome to nHybridChipTechnologies.com!"; print "$strn"; # This is case of non-interpolation. $str = 'Welcome to nHybridChipTechnologies.com!'; print "$strn"; # Only W will become upper case. $str = "uwelcome to HybridChipTechnologies.com!"; print "$strn"; # Whole line will become capital. $str = "UWelcome to HybridChipTechnologies.com!"; print "$strn"; # A portion of line will become capital. $str = "Welcome to UHybridChipTechnologiesE.com!"; print "$strn"; # Backsalash non alpha-numeric including spaces. $str = "QWelcome to HybridChipTechnologies's family"; print "$strn"; 13
  • 14. Welcome to HybridChipTechnologies.com! Welcome to nHybridChipTechnologies.com! Welcome to HybridChipTechnologies.com! WELCOME TO HYBRIDCHIPTECHNOLOGIES.COM! Welcome to HYBRIDCHIPTECHNOLOGIES.com! Welcome to HybridChipTechnologies's family OUTPUT : 14
  • 15. 15
  • 16. SCALAR VARIABLES :  A scalar is a single unit of data. That data might be an integer number, floating point, a character, a string, a paragraph, or an entire web page. Simply saying it could be anything, but only a single thing. EXAMPLE : #!/usr/bin/perl $age = 25; # An integer assignment $name = "John Paul"; # A string $salary = 1445.50; # A floating point print "Age = $agen"; print "Name = $namen"; print "Salary = $salaryn"; OUTPUT : Age = 25 Name = John Paul Salary = 1445.5 16
  • 17. 17
  • 18. ARRAY VARIABLES :  An array is a variable that stores an ordered list of scalar values. Array variables are preceded by an "at" (@) sign. To refer to a single element of an array, you will use the dollar sign ($) with the variable name followed by the index of the element in square brackets. PROGRAM : #!/usr/bin/perl @ages = (25, 30, 40); @names = ("John Paul", "Lisa", "Kumar"); print "$ages[0] = $ages[0]n"; print "$ages[1] = $ages[1]n"; print "$ages[2] = $ages[2]n"; print "$names[0] = $names[0]n"; print "$names[1] = $names[1]n"; print "$names[2] = $names[2]n"; OUTPUT : $ages[0] = 25 $ages[1] = 30 $ages[2] = 40 $names[0] = John Paul $names[1] = Lisa $names[2] = Kumar 18
  • 19. 19
  • 20. HASH VARIABLES :  A hash is a set of key/value pairs. Hash variables are preceded by a percent (%) sign. To refer to a single element of a hash, you will use the hash variable name followed by the "key" associated with the value in curly brackets. PROGRAM : #!/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"; OUTPUT : $data{'John Paul'} = 45 $data{'Lisa'} = 30 $data{'Kumar'} = 40 20
  • 21. 21
  • 22. VARIABLE CONTEXT :  Perl treats same variable differently based on Context, i.e. situation where a variable is being used. PROGRAM #!/usr/bin/perl @names = ('John Paul', 'Lisa', 'Kumar'); @copy = @names; $size = @names; print "Given names are : @copyn"; print "Number of names are : $sizen"; OUTPUT Given names are : John Paul Lisa Kumar Number of names are : 3 22
  • 23. S.N Context and Description 1 Scalar −Assignment to a scalar variable evaluates the right-hand side in a scalar context. 2 List −Assignment to an array or a hash evaluates the right-hand side in a list context. 3 Interpolative −This context only happens inside quotes, or things that work like quotes. 4 Void −This context not only doesn't care what the return value is, it doesn't even want a return value. 23
  • 24. 24
  • 25. CONDITIONAL STATEMENTS : Statement Description if statement An if statement consists of a boolean expression followed by one or more statements. if...else statement An if statement can be followed by an optional else statement. if...elsif...else statement An if statement can be followed by an optional elsif statement and then by an optional else statement. unless statement An unless statement consists of a boolean expression followed by one or more statements. unless...else statement An unless statement can be followed by an optionalelse statement. unless...elsif..else statement An unless statement can be followed by an optionalelsif statement and then by an optional else statement. switch statement With the latest versions of Perl, you can make use of theswitch statement. which allows a simple way of comparing a variable value against various conditions. 25
  • 26.  The number 0, the strings '0' and "" , the empty list () , and undef are all falsein a boolean context and all other values are true. Negation of a true value by ! or not returns a special false value. The syntax of an if statement in Perl programming language is − if(boolean_expression) { # statement(s) will execute if the given condition is true } 26
  • 27. OUTPUT a is less than 20 value of a is : 10 value of a is : PROGRAM #!/usr/local/bin/perl $a = 10; # check the boolean condition using if statement if( $a < 20 ) { # if condition is true then print the following print "a is less than 20n"; } print "value of a is : $an"; $a = ""; # check the boolean condition using if statement if( $a ) { # if condition is true then print the following print "a has a true valuen"; } print "value of a is : $an"; Explanation:  First IF statement makes use of less than operator (<), which compares two operands and if first operand is less than the second one then it returns true otherwise it returns false. 27
  • 28. if(boolean_expression){ # statement(s) will execute if the given condition is true } else{ # statement(s) will execute if the given condition is false }  The number 0, the strings '0' and "" , the empty list () , and undef are all falsein a boolean context and all other values are true. Negation of a true value by ! or not returns a special false value. 28
  • 29. PROGRAM #!/usr/local/bin/perl $a = 100; # check the boolean condition using if statement if( $a < 20 ){ # if condition is true then print the following printf "a is less than 20n"; } else{ # if condition is false then print the following printf "a is greater than 20n"; } print "value of a is : $an"; $a = ""; # check the boolean condition using if statement if( $a ){ # if condition is true then print the following printf "a has a true valuen"; } else{ # if condition is false then print the following printf "a has a false valuen"; } OUTPUT a is greater than 20 value of a is : 100 a has a false value value of a is : 29
  • 30. 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(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 } 30
  • 31. OUTPUT a has a value which is 100 PROGRAM #!/usr/local/bin/perl $a = 100; # check the boolean condition using if statement if( $a == 20 ){ # if condition is true then print the following printf "a has a value which is 20n"; }elsif( $a == 30 ){ # if condition is true then print the following printf "a has a value which is 30n"; }else{ # if none of the above conditions is true printf "a has a value which is $an"; } Explanation:  Here we are using the equality operator == which is used to check if two operands are equal or not.  If both the operands are same, then it returns true otherwise it retruns false. 31
  • 32.  If the boolean expression evaluates to false, then the block of code inside the unless statement will be executed.  If boolean expression evaluates to true then the first set of code after the end of the unless statement (after the closing curly brace) will be executed. unless(boolean_expression) { # statement(s) will execute if the given condition is false } 32
  • 33. OUTPUT a is not less than 20 value of a is : 20 a has a false value value of a is : Explanation:  First unless statement makes use of less than operator (<), which compares two operands and if first operand is less than the second one then it returns true otherwise it returns false. PROGRAM #!/usr/local/bin/perl $a = 20; # check the boolean condition using unless statement unless( $a < 20 ){ # if condition is false then print the following printf "a is not less than 20n"; } print "value of a is : $an"; $a = ""; # check the boolean condition using unless statement unless ( $a ){ # if condition is false then print the following printf "a has a false valuen"; } print "value of a is : $an"; 33
  • 34.  The number 0, the strings '0' and "" , the empty list () , and undef are all falsein a boolean context and all other values are true. Negation of a true value by ! or not returns a special false value. unless(boolean_expression){ # statement(s) will execute if the given condition is false } else{ # statement(s) will execute if the given condition is true } 34
  • 35. OUTPUT given condition is false value of a is : 100 a has a false value value of a is : PROGRAM #!/usr/local/bin/perl $a = 100; # check the boolean condition using unless statement unless( $a == 20 ){ # if condition is false then print the following printf "given condition is falsen"; }else{ # if condition is true then print the following printf "given condition is truen"; } print "value of a is : $an“; $a = ""; # check the boolean condition using unless statement unless( $a ){ # if condition is false then print the following printf "a has a false valuen"; }else{ # if condition is true then print the following printf "a has a true valuen"; } print "value of a is : $an"; printf "a has a false valuen"; } print "value of a is : $an“; 35
  • 36. When using unless , elsif , else statements there are few points to keep in mind.  An unless can have zero or one else's and it must come after any elsif's.  An unless 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. 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 } 36
  • 37. OUTPUT a has a value which is not 20 Explanation:  Here we are using the equality operator == which is used to check if two operands are equal or not. If both the operands are same then it returns true, otherwise it retruns false. PROGRAM #!/usr/local/bin/perl $a = 20; # check the boolean condition using if statement unless( $a == 30 ){ # if condition is false then print the following printf "a has a value which is not 20n"; }elsif( $a == 30 ){ # if condition is true then print the following printf "a has a value which is 30n"; }else{ # if none of the above conditions is met printf "a has a value which is $an"; } 37
  • 38. 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" } } 38
  • 39. OUTPUT number 100 number in list PROGRAM #!/usr/local/bin/perl use Switch; $var = 10; @array = (10, 20, 30); %hash = ('key1' => 10, 'key2' => 20); switch($var){ case 10 { print "number 100n"; next; } 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" } } 39
  • 40. 40
  • 41. INTRODUCTION :  There may be a situation when you need to execute a block of code several number of times. In general, statements are executed sequentially: The first statement in a function is executed first, followed by the second, and so on.  Programming languages provide various control structures that allow for more complicated execution paths. 41
  • 42. Loop Type Description while loop Repeats a statement or group of statements while a given condition is true. It tests the condition before executing the loop body. until loop Repeats a statement or group of statements until a given condition becomes true. It tests the condition before executing the loop body. for loop Executes a sequence of statements multiple times and abbreviates the code that manages the loop variable. foreach loop The for each loop iterates over a normal list value and sets the variable VAR to be each element of the list in turn. do...while loop Like a while statement, except that it tests the condition at the end of the loop body. nested loops You can use one or more loop inside any another while, for or do..while loop. 42
  • 43. while(condition) { statement(s); }  The number 0, the strings '0' and "" , the empty list () , and undef are all falsein a boolean context and all other values are true. Negation of a true value by ! or not returns a special false value. 43
  • 44. Explanation:  Here we are using the comparison operator < to compare value of variable $a against 20. So while value of $a is less than 20, while loop continues executing a block of code next to it and as soon as the value of $a becomes equal to 20, it comes out. PROGRAM #!/usr/local/bin/perl $a = 10; # while loop execution while( $a < 20 ){ printf "Value of a: $an"; $a = $a + 1; } OUTPUT Value of a: 10 Value of a: 11 Value of a: 12 Value of a: 13 Value of a: 14 Value of a: 15 Value of a: 16 Value of a: 17 Value of a: 18 Value of a: 19 44
  • 45. until(condition) { statement(s); }  The number 0, the strings '0' and "" , the empty list () , and undef are all falsein a boolean context and all other values are true. Negation of a true value by ! or not returns a special false value. 45
  • 46. Explanation:  Here we are using the comparison operator > to compare value of variable $a against 10. So until the value of $a is less than 10, until loop continues executing a block of code next to it and as soon as the value of $a becomes greater than 10, it comes out. OUTPUT Value of a: 5 Value of a: 6 Value of a: 7 Value of a: 8 Value of a: 9 Value of a: 10 PROGRAM #!/usr/local/bin/perl $a = 5; # until loop execution until( $a > 10 ){ printf "Value of a: $an"; $a = $a + 1; } 46
  • 47. for ( init; condition; increment ) { statement(s); } Here is the flow of control in a for loop −  The init step is executed first, and only once. This step allows you to declare and initialize any loop control variables. You are not required to put a statement here, as long as a semicolon appears.  Next, the condition is evaluated. If it is true, the body of the loop is executed. If it is false, the body of the loop does not execute and flow of control jumps to the next statement just after the for loop.  After the body of the for loop executes, the flow of control jumps back up to theincrement statement. This statement allows you to update any loop control variables. This statement can be left blank, as long as a semicolon appears after the condition.  The condition is now evaluated again. If it is true, the loop executes and the process repeats itself (body of loop, then increment step, and then again condition). After the condition becomes false, the for loop terminates. 47
  • 48. OUTPUT value of a: 10 value of a: 11 value of a: 12 value of a: 13 value of a: 14 value of a: 15 value of a: 16 value of a: 17 value of a: 18 value of a: 19 PROGRAM #!/usr/local/bin/perl # for loop execution for( $a = 10; $a < 20; $a = $a + 1 ){ print "value of a: $an"; } 48
  • 50. PROGRAM #!/usr/local/bin/perl @list = (2, 20, 30, 40, 50); # foreach loop execution foreach $a (@list){ print "value of a: $an"; } OUTPUT value of a: 2 value of a: 20 value of a: 30 value of a: 40 value of a: 50 50
  • 51. do { statement(s); }while( condition );  The number 0, the strings '0' and "" , the empty list () , and undef are all falsein a boolean context and all other values are true. Negation of a true value by ! or not returns a special false value. 51
  • 52. OUTPUT Value of a: 10 Value of a: 11 Value of a: 12 Value of a: 13 Value of a: 14 Value of a: 15 Value of a: 16 Value of a: 17 Value of a: 18 Value of a: 19 PROGRAM #!/usr/local/bin/perl @list = (2, 20, 30, 40, 50); # fo#!/usr/local/bin/perl $a = 10; # do...while loop execution do{ printf "Value of a: $an"; $a = $a + 1; }while( $a < 20 ); reach loop execution foreach $a (@list){ print "value of a: $an"; } 52
  • 53. for ( init; condition; increment ){ for ( init; condition; increment ){ statement(s); } statement(s); } while(condition){ while(condition){ statement(s); } statement(s); } do{ statement(s); do{ statement(s); }while( condition ); }while( condition ); until(condition){ until(condition){ statement(s); } statement(s); } foreach $a (@listA){ foreach $b (@listB){ statement(s); } statement(s); } 53
  • 54. PROGRAM foreach $a (@listA){ foreach $b (@listB){ statement(s); } statement(s); #/usr/local/bin/perl $a = 0; $b = 0; # outer while loop while($a < 3){ $b = 0; # inner while loop while( $b < 3 ){ print "value of a = $a, b = $bn"; $b = $b + 1; } $a = $a + 1; print "Value of a = $ann"; } } OUTPUT value of a = 0, b = 0 value of a = 0, b = 1 value of a = 0, b = 2 Value of a = 1 value of a = 1, b = 0 value of a = 1, b = 1 value of a = 1, b = 2 Value of a = 2 value of a = 2, b = 0 value of a = 2, b = 1 value of a = 2, b = 2 Value of a = 3 54
  • 55. Control Statement Description next statement Causes the loop to skip the remainder of its body and immediately retest its condition prior to reiterating. last statement Terminates the loop statement and transfers execution to the statement immediately following the loop. continue statement A continue BLOCK, it is always executed just before the conditional is about to be evaluated again. redo statement The redo command restarts the loop block without evaluating the conditional again. The continue block, if any, is not executed. goto statement Perl supports a goto command with three forms: goto label, goto expr, and goto &name. 55
  • 56. 56
  • 57. Simple answer can be given using the expression 4 + 5 is equal to 9. Here 4 and 5 are called operands and + is called operator. Perl language supports many operator types  Arithmetic Operators  Equality Operators  Logical Operators  Assignment Operators  Bitwise Operators  Logical Operators  Quote-like Operators  Miscellaneous Operators 57
  • 58. Operator Description Example + Addition - Adds values on either side of the operator $a + $b will give 30 - Subtraction - Subtracts right hand operand from left hand operand $a - $b will give -10 * Multiplication - Multiplies values on either side of the operator $a * $b will give 200 / Division - Divides left hand operand by right hand operand $b / $a will give 2 % Modulus - Divides left hand operand by right hand operand and returns remainder $b % $a will give 0 ** Exponent - Performs exponential (power) calculation on operators $a**$b will give 10 to the power 20 58
  • 59. 59
  • 60. 60
  • 61. 61
  • 62. 62
  • 63. 63
  • 64. 64
  • 65. left - terms and list operators (leftward) left - -> nonassoc - ++ -- right - ** right - ! ~ and unary + and - left - =~ !~ left - * / % x left - + - . left - << >> nonassoc - named unary operators nonassoc - < > <= >= lt gt le ge nonassoc - == != <=> eq ne cmp ~~ left - & left - | ^ left - && left - || // nonassoc - .. ... right - ?: right - = += -= *= etc. left - , => nonassoc - list operators (rightward) right - not left - and left - or xor 65
  • 66. 66
  • 67.  Current Date & Time  GMT Time  Format Date & Time  Epoch time  POSIX Function strftime() 67
  • 68.  Let's start with localtime() function, which returns values for the current date and time if given no arguments. Following is the 9-element list returned by the localtime function Variables: sec, # seconds of minutes from 0 to 61 min, # minutes of hour from 0 to 59 hour, # hours of day from 0 to 24 mday, # day of month from 1 to 31 mon, # month of year from 0 to 11 year, # year since 1900 wday, # days since sunday yday, # days since January 1st isdst # hours of daylight savings time Program 1: #!/usr/local/bin/perl @months = qw( Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec ); @days = qw(Sun Mon Tue Wed Thu Fri Sat Sun); ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$is dst) = localtime(); print "$mday $months[$mon] $days[$wday]n"; Program 1: #!/usr/local/bin/perl $datestring = localtime(); print "Local date and time $datestringn"; Output 1: 16 Feb Sat Output 2: Local date and time Sat Feb 16 06:50:45 2013 68
  • 69.  The function gmtime() works just like localtime() function but the returned values are localized for the standard Greenwich time zone. When called in list context, $isdst, the last value returned by gmtime, is always 0 . There is no Daylight Saving Time in GMT.  You should make a note on the fact that localtime() will return the current local time on the machine that runs the script and gmtime() will return the universal Greenwich Mean Time, or GMT (or UTC). PROGRAM #!/usr/local/bin/perl $datestring = gmtime(); print "GMT date and time $datestringn"; OUTPUT GMT date and time Sat Feb 16 13:50:45 2013 69
  • 70.  You can use localtime() function to get a list of 9-elements and later you can use the printf()function to format date and time based on your requirements OUTPUT Time Format - HH:MM:SS 06:58:52 PROGRAM #!/usr/local/bin/perl ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime(); printf("Time Format - HH:MM:SSn"); printf("%02d:%02d:%02d", $hour, $min, $sec); 70
  • 71.  You can use the time() function to get epoch time, i.e. the numbers of seconds that have elapsed since a given date, in Unix is January 1, 1970. PROGRAM #!/usr/local/bin/perl $epoc = time(); print "Number of seconds since Jan 1, 1970 - $epocn"; OUTPUT Number of seconds since Jan 1, 1970 - 1361022130 71
  • 72.  You can use the POSIX function strftime() to format date and time with the help of the following table. Please note that the specifiers marked with an asterisk (*) are locale-dependent. 72
  • 73. 73
  • 74. 74
  • 75.  Define and Call a Subroutine  Passing Arguments to a Subroutine  Passing Lists to Subroutines  Passing Hashes to Subroutines  Returning Value from a Subroutine  Private Variables in a Subroutine  Temporary Values via local()  State Variables via state()  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 usually is so each function performs a specific task. 75
  • 76. sub subroutine_name { body of the subroutine } PROGRAM #!/usr/bin/perl # Function definition sub Hello{ print "Hello, World!n"; } # Function call Hello(); OUTPUT Hello, World! The general form of a subroutine definition in Perl programming language 76
  • 77.  You can pass various arguments to a subroutine like you do in any other programming language and they can be acessed inside the function using the special array @_. Thus the first argument to the function is in $_[0], the second is in $_[1], and so on.  You can pass arrays and hashes as arguments like any scalar but passing more than one array or hash normally causes them to lose their separate identities. So we will use references ( explained in the next chapter ) to pass any array or hash. PROGRAM #!/usr/bin/perl # Function definition sub Average{ # get total number of arguments passed. $n = scalar(@_); $sum = 0; foreach $item (@_){ $sum += $item; } $average = $sum / $n; print "Average for the given numbers : $averagen"; } # Function call Average(10, 20, 30); OUTPUT Average for the given numbers : 20 77
  • 78.  Because the @_ variable is an array, it can be used to supply lists to a subroutine. However, because of the way in which Perl accepts and parses lists and arrays, it can be difficult to extract the individual elements from @_. If you have to pass a list along with other scalar arguments, then make list as the last argument PROGRAM #!/usr/bin/perl # Function definition sub PrintList{ my @list = @_; print "Given list is @listn"; } $a = 10; @b = (1, 2, 3, 4); # Function call with list parameter PrintList($a, @b); OUTPUT Given list is 10 1 2 3 4 78
  • 79.  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. PROGRAM #!/usr/bin/perl # Function definition sub PrintHash{ my (%hash) = @_; foreach my $key ( keys %hash ){ my $value = $hash{$key}; print "$key : $valuen"; } } %hash = ('name' => 'Tom', 'age' => 19); # Function call with hash parameter PrintHash(%hash); OUTPUT name : Tom age : 19 79
  • 80.  You can return a value from subroutine like you do in any other programming language. If you are not returning a value from a subroutine then whatever calculation is last performed in a subroutine is automatically also the return value.  You can return arrays and hashes from the subroutine like any scalar but returning more than one array or hash normally causes them to lose their separate identities. So we will use references ( explained in the next chapter ) to return any array or hash from a function. PROGRAM #!/usr/bin/perl # Function definition sub Average{ # get total number of arguments passed. $n = scalar(@_); $sum = 0; foreach $item (@_){ $sum += $item; } $average = $sum / $n; return $average; } # Function call $num = Average(10, 20, 30); print "Average for the given numbers : $numn"; OUTPUT Average for the given numbers : 20 80
  • 81.  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. sub somefunc { my $variable; # $variable is invisible outside somefunc() my ($another, @an_array, %a_hash); # declaring many variables at once } PROGRAM #!/usr/bin/perl # Global variable $string = "Hello, World!"; # Function definition sub PrintHello{ # Private variable for PrintHello function my $string; $string = "Hello, Perl!"; print "Inside the function $stringn"; } # Function call PrintHello(); print "Outside the function $stringn"; OUTPUT Inside the function Hello, Perl! Outside the function Hello, World! 81
  • 82.  The local is mostly used when the current value of a variable must be visible to called subroutines. A local just gives temporary values to global (meaning package) variables. This is known as dynamic scoping. Lexical scoping is done with my, which works more like C's auto declarations. #!/usr/bin/perl # Global variable $string = "Hello, World!"; sub PrintHello{ # Private variable for Print Hello function local $string; $string = "Hello, Perl!"; PrintMe(); print "Inside the function Print Hello $stringn"; } sub PrintMe{ print "Inside the function PrintMe $stringn"; } # Function call PrintHello(); print "Outside the function $stringn"; OUTPUT Inside the function PrintMe Hello, Perl! Inside the function PrintHello Hello, Perl! Outside the function Hello, World! 82
  • 83.  There are another type of lexical variables, which are similar to private variables but they maintain their state and they do not get reinitialized upon multiple calls of the subroutines. These variables are defined using the state operator and available starting from Perl PROGRAM #!/usr/bin/perl use feature 'state'; sub PrintCount{ state $count = 0; # initial value print "Value of counter is $countn"; $count++; } for (1..5){ PrintCount(); } OUTPUT Value of counter is 0 Value of counter is 1 Value of counter is 2 Value of counter is 3 Value of counter is 4 83
  • 84. 84
  • 85.  A Perl reference is a scalar data type that holds the location of another value which could be scalar, arrays, or hashes. Because of its scalar nature, a reference can be used anywhere, a scalar can be used.  Create References  Dereferencing  Circular References  References to Functions 85
  • 86.  It is easy to create a reference for any variable, subroutine or value by prefixing it with a backslash. $scalarref = $foo; $arrayref = @ARGV; $hashref = %ENV; $coderef = &handler; $globref = *foo;  You cannot create a reference on an I/O handle (filehandle or dirhandle) using the backslash operator but a reference to an anonymous array can be created using the square brackets. $arrayref = [1, 2, ['a', 'b', 'c']];  Similar way you can create a reference to an anonymous hash using the curly brackets. $hashref = { 'Adam' => 'Eve', 'Clyde' => 'Bonnie', }; 86
  • 87. PROGRAM #!/usr/bin/perl $var = 10; $r = $var; print "Reference type in r : ", ref($r), "n"; @var = (1, 2, 3); $r = @var; print "Reference type in r : ", ref($r), "n"; %var = ('key1' => 10, 'key2' => 20); $r = %var; print "Reference type in r : ", ref($r), "n";  Dereferencing returns the value from a reference point to the location. To dereference a reference simply use $, @ or % as prefix of the reference variable depending on whether the reference is pointing to a scalar, array, or hash. OUTPUT Reference type in r : SCALAR Reference type in r : ARRAY Reference type in r : HASH 87
  • 88.  A circular reference occurs when two references contain a reference to each other. You have to be careful while creating references otherwise a circular reference can lead to memory leaks. PROGRAM #!/usr/bin/perl my $foo = 100; $foo = $foo; print "Value of foo is : ", $$foo, "n"; OUTPUT Value of foo is : REF(0x9aae38) 88
  • 89.  This might happen if you need to create a signal handler so you can produce a reference to a function by preceding that function name with & and to dereference that reference you simply need to prefix reference variable using ampersand &. PROGRAM #!/usr/bin/perl # Function definition sub PrintHash{ my (%hash) = @_; foreach $item (%hash){ print "Item : $itemn"; } } %hash = ('name' => 'Tom', 'age' => 19); # Create a reference to above function. $cref = &PrintHash; # Function call using reference. &$cref(%hash); OUTPUT Item : name Item : Tom Item : age Item : 19 89
  • 90. 90
  • 91.  Perl uses a writing template called a 'format' to output reports. To use the format feature of Perl, you have to define a format first and then you can use that format to write formatted data. 91  Define a Format  Using the Format  Define a Report Header  Define a Pagination  Perl - Special Variables
  • 92. 92 format FormatName = fieldline value_one, value_two, value_three fieldline value_one, value_two  Here FormatName represents the name of the format. The fieldline is the specific way, the data should be formatted. The values lines represent the values that will be entered into the field line. You end the format with a single period.  Next fieldline can contain any text or fieldholders. The fieldholders hold space for data that will be placed there at a later date. PROGRAM format EMPLOYEE = =================================== @<<<<<<<<<<<<<<<<<<<<<< @<< $name $age @#####.## $salary =================================== EXPLANATION  In this example, $name would be written as left justify within 22 character spaces and after that age will be written in two spaces.
  • 93. 93  In order to invoke this format declaration, we would use the write keyword − write EMPLOYEE;  The problem is that the format name is usually the name of an open file handle, and the write statement will send the output to this file handle. As we want the data sent to the STDOUT, we must associate EMPLOYEE with the STDOUT file handle. First, however, we must make sure that that STDOUT is our selected file handle, using the select() function. select(STDOUT);  We would then associate EMPLOYEE with STDOUT by setting the new format name with STDOUT, using the special variable $~ or $FORMAT_NAME as follows − $~ = "EMPLOYEE";  When we now do a write(), the data would be sent to STDOUT. Remember: if you are going to write your report in any other file handle instead of STDOUT then you can use select() function to select that file handle and rest of the logic will remain the same.
  • 94. 94  Let's take the following example. Here we have hard coded values just for showing the usage. In actual usage you will read values from a file or database to generate actual reports and you may need to write final report again into a file. PROGRAM #!/usr/bin/perl format EMPLOYEE = ======================= @<<<<<<<<<<<<<<<<<<<<<< @<< $name $age @#####.## $salary ====================== . select(STDOUT); $~ = EMPLOYEE; @n = ("Ali", "Raza", "Jaffer"); @a = (20,30, 40); @s = (2000.00, 2500.00, 4000.000); $i = 0; foreach (@n){ $name = $_; $age = $a[$i]; $salary = $s[$i++]; write; } OUTPUT ========================= Ali 20 2000.00 ========================= ========================= Raza 30 2500.00 ========================= ========================= Jaffer 40 4000.00 =========================
  • 95. 95  Everything looks fine. But you would be interested in adding a header to your report. This header will be printed on top of each page. It is very simple to do this. Apart from defining a template you would have to define a header and assign it to $^ or $FORMAT_TOP_NAME variable. PROGRAM #!/usr/bin/perl format EMPLOYEE = ======================== @<<<<<<<<<<<<<<<<<<<<<< @<< $name $age @#####.## $salary ======================== . format EMPLOYEE_TOP = ======================== Name Age ======================== . select(STDOUT); $~ = EMPLOYEE; $^ = EMPLOYEE_TOP; @n = ("Ali", "Raza", "Jaffer"); @a = (20,30, 40); @s = (2000.00, 2500.00, 4000.000); $i = 0; foreach (@n){ $name = $_; $age = $a[$i]; $salary = $s[$i++]; write; } OUTPUT ===================== Name Age ===================== ===================== Ali 20 2000.00 ===================== ===================== Raza 30 2500.00 ===================== ===================== Jaffer 40 4000.00 =====================
  • 96. 96  What about if your report is taking more than one page? You have a solution for that, simply use $% or $FORMAT_PAGE_NUMBER vairable along with header. PROGRAM format EMPLOYEE_TOP = ======================= Name Age Page @< $% ======================= . OUTPUT ====================== Name Age Page 1 ====================== ====================== Ali 20 2000.00 ====================== ====================== Raza 30 2500.00 ====================== ====================== Jaffer 40 4000.00 ====================== HINT  You can set the number of lines per page using special variable $= ( or $FORMAT_LINES_PER_PAG E ), By default $= will be 60.
  • 97. 97
  • 98. 98  The basics of handling files are simple: you associate a filehandle with an external entity (usually a file) and then use a variety of operators and functions within Perl to read and update the data stored within the data stream associated with the filehandle.  Opening and Closing Files  Open Function  Sysopen Function  Close Function  Reading and Writing Files
  • 99. 99  There are following two functions with multiple forms, which can be used to open any new or existing file in Perl. open FILEHANDLE, EXPR open FILEHANDLE sysopen FILEHANDLE, FILENAME, MODE, PERMS sysopen FILEHANDLE, FILENAME, MODE  Here FILEHANDLE is the file handle returned by the open function and EXPR is the expression having file name and mode of opening the file.
  • 100. 100  Following is the syntax to open file.txt in read-only mode. Here less than < sign indicates that file has to be opend in read-only mode. open(DATA, "<file.txt");  Here DATA is the file handle which will be used to read the file. Here is the example which will open a file and will print its content over the screen. #!/usr/bin/perl open(DATA, "<file.txt") or die "Couldn't open file file.txt, $!“; while(<DATA>){ print "$_"; }  Following is the syntax to open file.txt in writing mode. Here less than > sign indicates that file has to be opend in the writing mode. open(DATA, ">file.txt") or die "Couldn't open file file.txt, $!";
  • 101. 101  For example, to open a file for updating without truncating it − open(DATA, "+<file.txt"); or die "Couldn't open file file.txt, $!";  To truncate the file first − open DATA, "+>file.txt" or die "Couldn't open file file.txt, $!";  You can open a file in the append mode. In this mode writing point will be set to the end of the file. open(DATA,">>file.txt") || die "Couldn't open file file.txt, $!";  A double >> opens the file for appending, placing the file pointer at the end, so that you can immediately start appending information. However, you can't read from it unless you also place a plus sign in front of it − open(DATA,"+>>file.txt") || die "Couldn't open file file.txt, $!";
  • 102. 102  The sysopen function is similar to the main open function, except that it uses the systemopen() function, using the parameters supplied to it as the parameters for the system function. sysopen(DATA, "file.txt", O_RDWR);  truncate the file before updating sysopen(DATA, "file.txt", O_RDWR|O_TRUNC );  The PERMS argument specifies the file permissions for the file specified if it has to be created. By default it takes 0x666.
  • 103. 103  To close a filehandle, and therefore disassociate the filehandle from the corresponding file, you use the close function. This flushes the filehandle's buffers and closes the system's file descriptor. close FILEHANDLE close  If no FILEHANDLE is specified, then it closes the currently selected filehandle. It returns true only if it could successfully flush the buffers and close the file. close(DATA) || die "Couldn't close file properly";
  • 104. 104  Once you have an open file handle, you need to be able to read and write information. There are a number of different ways of reading and writing data into the file.  getc Function  read Function  print Function  Copying Files
  • 105. 105  The getc function returns a single character from the specified FILEHANDLE, or STDIN if none is specified getc FILEHANDLE getc  The read function reads a block of information from the buffered filehandle: This function is used to read binary data from the file. read FILEHANDLE, SCALAR, LENGTH, OFFSET read FILEHANDLE, SCALAR, LENGTH  The print function prints the evaluated value of LIST to FILEHANDLE, or to the current output file handle (STDOUT by default). print "Hello World!n";
  • 106. 106  Here is the example, which opens an existing file file1.txt and read it line by line and generate another copy file file2.txt. #!/usr/bin/perl # Open file to read open(DATA1, "<file1.txt"); # Open new file to write open(DATA2, ">file2.txt"); # Copy data fro
  • 107. 107
  • 108. 108  Most of the special variables have an english like long name, e.g., Operating System Error variable $! can be written as $OS_ERROR. But if you are going to use english like names, then you would have to put one line use English; at the top of your program file. This guides the interpreter to pickup exact meaning of the variable.  Global Scalar Special Variables.  Global Array Special Variables.  Global Hash Special Variables.  Global Special File handles.  Global Special Constants.  Regular Expression Special Variables.  File handle Special Variables.
  • 109. 109
  • 110. 110
  • 111. 111
  • 112. 112 Symbol Description @ARGV The array containing the command-line arguments intended for the script. @INC The array containing the list of places to look for Perl scripts to be evaluated by the do, require, or use constructs. @F The array into which the input lines are split when the -a command-line switch is given.
  • 113. 113 Symbol Description %INC The hash containing entries for the filename of each file that has been included via do or require. %ENV The hash containing your current environment. %SIG The hash used to set signal handlers for various signals.
  • 114. 114 Symbol Description ARGV The special filehandle that iterates over command line filenames in @ARGV. Usually written as the null filehandle in <>. STDERR The special filehandle for standard error in any package. STDIN The special filehandle for standard input in any package. STDOUT The special filehandle for standard output in any package. DATA The special filehandle that refers to anything following the __END__ token in the file containing the script. Or, the special filehandle for anything following the __DATA__ token in a required file, as long as you're reading data in the same package __DATA__ was found in. _ (underscore) The special filehandle used to cache the information from the last stat, lstat, or file test operator.
  • 115. 115 Symbol Description __END__ Indicates the logical end of your program. Any following text is ignored, but may be read via the DATA filehandle. __FILE__ Represents the filename at the point in your program where it's used. Not interpolated into strings. __LINE__ Represents the current line number. Not interpolated into strings. __PACKAGE__ Represents the current package name at compile time, or undefined if there is no current package. Not interpolated into strings.
  • 116. 116 Symbol Description $digit Contains the text matched by the corresponding set of parentheses in the last pattern matched. For example, $1 matches whatever was contained in the first set of parentheses in the previous regular expression. $&, $MATCH The string matched by the last successful pattern match. $`, $PREMATCH The string preceding whatever was matched by the last successful pattern match. $‘, $POSTMATCH The string following whatever was matched by the last successful pattern match. $+, $LAST_PAREN_MATCH The last bracket matched by the last search pattern. This is useful if you don't know which of a set of alternative patterns was matched. For example: /Version: (.*)|Revision: (.*)/ && ($rev = $+);
  • 117. 117
  • 118. 118
  • 119. 119  Perl - Socket Programming  Perl – Object Oriented  Perl – Database Access  Perl – CGI Programming  Perl – Packages and Modules  Perl – Process Management  Perl – Embedded Documentation
  • 120. 120  Socket is a Berkeley UNIX mechanism of creating a virtual duplex connection between different processes. This was later ported on to every known OS enabling communication between systems across geographical location running on different OS software. If not for the socket, most of the network communication between systems would never ever have happened.  To Create a Server  To Create a Client  Server Side Socket Calls  The bind() call  The listen() call  The accept() call  Client Side Socket Calls  The connect() call
  • 121. 121  We have already studied references in Perl and Perl anonymous arrays and hashes. Object Oriented concept in Perl is very much based on references and anonymous array and hashes. Let's start learning basic concepts of Object Oriented Perl.  Object Basics  Defining a Class  Creating and Using Objects  Defining Methods  Inheritance  Method Overriding  Default Auto loading  Destructors and Garbage Collection
  • 122. 122  DBI stands for Database Independent Interface for Perl, which means DBI provides an abstraction layer between the Perl code and the underlying database, allowing you to switch database implementations really easily.  The DBI is a database access module for the Perl programming language. It provides a set of methods, variables, and conventions that provide a consistent database interface, independent of the actual database being used. Architecture of DBI - Databases
  • 123. 123  Notation and Conventions  Database Connection  INSERT Operation  Using Bind Values  READ Operation  UPDATE Operation  DELETE Operation  COMMIT Operation  ROLLBACK Operation  Begin Transaction  Auto Commit Option  Automatic Error Handling  Disconnecting Database  Using NULL Values  Some Other DBI Functions
  • 124. 124  A Common Gateway Interface, or CGI, is a set of standards that defines how information is exchanged between the web server and a custom script.  The CGI specifications are currently maintained by the NCSA and NCSA defines CGI is as follows −  The Common Gateway Interface, or CGI, is a standard for external gateway programs to interface with information servers such as HTTP servers.  The current version is CGI/1.1 and CGI/1.2 is under progress. Architecture of CGI Programming
  • 125. 125  First CGI Program  Understanding HTTP Header  CGI Environment Variables  Raise a "File Download" Dialog Box?  GET and POST Methods  Passing Information using GET Method  Simple URL Example: Get Method  Simple FORM Example: GET Method  Passing Information using POST Method  Passing Checkbox Data to CGI Program  Passing Radio Button Data to CGI Program  Passing Text Area Data to CGI Program  Passing Drop Down Box Data to CGI Program  Using Cookies in CGI  CGI Modules and Libraries
  • 126. 126  A package is a collection of code which lives in its own namespace.  A namespace is a named collection of unique variable names (also called a symbol table).  Namespaces prevent variable name collisions between packages.  Packages enable the construction of modules which, when used, won't clobber variables and functions outside of the modules's own namespace.  The package stays in effect until either another package statement is invoked, or until the end of the current block or file.  You can explicitly refer to variables within a package using the :: package qualifier.  BEGIN and END Blocks  What are Perl Modules?  The Require Function  The Use Function  Create the Perl Module Tree  Installing Perl Module
  • 127. 127 You can use Perl in various ways to create new processes as per your requirements. This tutorial will list down few important and most frequently used methods of creating and managing Perl processes.  You can use special variables $$ or $PROCESS_ID to get current process ID.  Every process created using any of the mentioned methods, maintains its own virtual environment with-in %ENV variable.  The exit() function always exits just the child process which executes this function and the main process as a whole will not exit unless all running child-processes have exited.  All open handles are dup()-ed in child-processes, so that closing any handles in one process does not affect the others.  Backstick Operator  The system() Function  The fork() Function  The kill() Function
  • 128. 128  You can embed Pod (Plain Old Text) documentation in your Perl modules and scripts. Following is the rule to use embedded documentation in your Perl Code. What is POD?  Pod is a simple-to-use markup language used for writing documentation for Perl, Perl programs, and Perl modules. There are various translators available for converting Pod to various formats like plain text, HTML, man pages, and more. Pod markup consists of three basic kinds of paragraphs −  Ordinary Paragraph: You can use formatting codes in ordinary paragraphs, for bold, italic, code-style , hyperlinks, and more.  Verbatim Paragraph: Verbatim paragraphs are usually used for presenting a codeblock or other text which does not require any special parsing or formatting, and which shouldn't be wrapped.  Command Paragraph: A command paragraph is used for special treatment of whole chunks of text, usually as headings or parts of lists. All command paragraphs start with =, followed by an identifier, followed by arbitrary text that the command can use however it pleases. Currently recognized commands.
  • 129. 129
  翻译: