Unit 3
Unit 3
Perl
Practical Extraction and Reporting Language
Introduction to Perl
• There is no official Full form of the Perl, but still, the most used expansion is “Practical
Extraction and Reporting Language“.
• Perl is a lot similar to C syntactically and is easy for the users who have knowledge of C
, C++.
Why Perl?
• Web and Perl: Perl can be embedded into web servers to increase its processing power
and it has the DBI package, which makes web-database integration very easy.
Applications of Perl
• Perl is one of the most widely used language over the web.
• Perl used to be the most popular web programming language due to its text manipulation
capabilities and rapid development cycle.
• It is very efficient in text-manipulation i.e. Regular Expression. It also provides the socket
capability.
• It is an embeddable language that’s why it can embed in web servers and database servers.
• It supports more than 25, 000 open source modules on which provide many powerful
extensions to the standard library. For example, XML processing, GUI(Graphical User
Interface) and DI(Database Integration) etc.
First Perl Program:
Print “hello world”;
Perl File Extension:
a Perl file must be saved with a .pl or .PL file extension.
Comments in Perl:
# This is a single line comment
=begin comment This is all part of multiline comment. You can use as many lines as
you like These comments will be ignored by the compiler until the next =cut is
encountered. =cut
How to Run a Perl Program?
• Using Command-Line: You can also use command line options to run a Perl program.
Below steps demonstrate how to run a Perl program on Command line in Windows/Unix
Operating System:
Windows
• Perl language is a loosely typed language, the Perl interpreter itself chooses the data type.
Hence, there is no need to specify data type in Perl programming.
• Scalars: Perl scalars are a single data item. They are simple variables, preceded by a ($)
sign. A scalar can be a number, a reference (address of a variable) or a string.
• Arrays: Perl arrays are an ordered list of scalars. They are preceded by (@) sign and
accessed by their index number which starts with 0.
• Hashes: Perl hashes are an unordered collection of key-value pairs. They are preceded by
(%) sign and accessed using keys.
Naming Convention for scalers
Perl has three rules for naming scalars
1.All scalar names will begin with a $. It is easy is to remember to prefix every name with
$.
2.Like PHP. after the first character $, which, is special in Perl, alphanumeric characters i.e.
a to z, A to Z and 0 to 9 are allowed. Underscore character is also allowed. Use
underscore to split the variable names into two words. `But the First character cannot be a
number.
3.Even though numbers can be part of the name, they cannot come immediately after $.
This implies that first character after $ will be either an alphabet or the underscore.
Perl Example:
$var;
$Var32;
$vaRRR43;
$name_underscore_23;
• Two Types of Scalar Data Types
1.Numbers
2.Strings
Numbers:
In this type of scalar data we could specify:
Notice: In general, Perl interpreter sees integers like floating points numbers. For example,
if you write 2 in your programs, Perl will see it like 2.0000
Floating-point literals:
• It consists of digits, optionally minus, decimal point and exponent.
Strings
• The maximum length of a string in Perl depends upon the amount of memory the
computer has. There is no limit to the size of the string, any amount of characters,
symbols, or words can make up your strings.
• The shortest string has no characters.
• The longest can fill all of the system memory.
Like numbers there are two different types of strings:
• Single quotes string literals
• Double quotes string literals
Single-quoted string literals
• Single quotation marks are used to enclose data
Double-quoted string literals
• Double quotation marks are used to enclose data that needs to be interpolated before
processing. That means that escaped characters and variables aren’t simply literally
inserted into later operations, but are evaluated on the spot. Escape characters can be used
to insert newlines, tabs, etc.
String Concatenation (period) :
• An Array is a special type of variable which stores data in the form of a list.
• Each element can be accessed using the index number which will be unique for each and
every element.
• You can store numbers, strings, floating values, etc. in your array.
• In Perl, you can define an array using ‘@’ character followed by the name that you want
to give. Let’s consider defining an array in Perl.
my @array;
3. Hashes(Associative Arrays):
NOTE: Declare a variable before we use it if we use use strict statement in our program.
• The operand to the left of the = operator is the name of the variable, and the operand to
the right of the = operator is the value stored in the variable.
For example −
$age = 25; # An integer assignment
$name = "John "; # A string
$salary = 1445.50; # A floating point
Here 25, "John " and 1445.50 are the values assigned to $age, $name and $salary variables,
respectively.
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.
OUTPUT
Array Variables
OUTPUT
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.
Scope of a variable – Access Modifiers
• We can declare a scalar in anywhere in the program. But you need to specify an access
modifier.
• There are 3 types of modifiers
1.my
2.local
3.our
My:
Using this you can declare any variable which is specific within the block. i.e. within
the curly braces.
My Access Modifiers
MY scope
• In these operators, {} will represent a pair of delimiters that user choose. In this category
there are three operators as follows:
q{ } : It will encloses a string in single quotes(”) and cannot interpolate the string
variable. For Example: q{hello} gives ‘hello’.
qq{ }: It will encloses a string in double quotes(“”) and can interpolate the string
variable. For Example: qq{hello} gives “hello”.
qx{ } : It will encloses a string in invert quotes(“). For Example: qx{hello} gives `hello`.
• Example:
Operators
For Example: $a = 5;
$b = 10;
print $a + $b;
Subtraction: ‘–‘ operator is used to subtract right hand operand from left hand operand.
For Example:
Modulus Operator: ‘%‘ operator is used to divide left hand operand from right operand
and returns remainder. For Example: $a = 10; $b = 15; print $a % $b;
For Example:
$a = 2;
$b = 3;
print $a**$b;
Not equal To Operator: ‘!=’ Check if the two values are equal or not. If not equal then
returns 1 otherwise returns nothing.
Comparison of equal to Operator: ‘< = >’ If left operand is less than right then returns -1,
if equal returns 0 else returns 1.
Greater than Operator: ‘>’ If left operand is greater than right returns 1 else returns
nothing.
Less than Operator: ‘<‘ If left operand is lesser than right returns 1 else returns
nothing.
Greater than equal to Operator: ‘>=’ If left operand is greater than or equal to right
returns 1 else returns nothing.
Less than equal to Operator: ‘<=’ If left operand is lesser than or equal to right returns
1 else returns nothing.
Logical Operators
• These operators are used to combine two or more conditions/constraints or to complement
the evaluation of the original condition in consideration.
Logical AND: The ‘and’ operator returns true when both the conditions in consideration
are satisfied. For example, $a and $b is true when both a and b both are true (i.e. non-
zero). You can use also &&.
Logical OR: The ‘or’ operator returns true when one (or both) of the conditions in
consideration is satisfied. For example, $a or $b is true if one of a or b is true (i.e. non-
zero). Of course, it gives result “true” when both a and b are true. You can use also ||
Logical NOT: The ‘not’ operator will give 1 if the condition in consideration is satisfied.
For example, not($d) is true if $d is 0.
Bitwise Operators
• These operators are used to perform the bitwise operation. It will first convert the number into bits and
perform the bit-level operation on the operands.
& (bitwise AND) Takes two numbers as operands and does AND on every bit of two numbers. The result of
AND is 1 only if both bits are 1. For example
$a = 13; // 1101
$b = 5; // 0101
Explanation:
$a = 1 1 0 1
$b = 0 1 0 1
$c = 0 1 0 1
| (bitwise OR) Takes two numbers as operands and does OR on every bit of two
numbers. The result of OR is 1 any of the two bits is 1. For example
$a = 13; // 1101
$b = 5; // 0101
$c = $b | $a;
print $c;
• Here Output will be 13
Explanation:
• $a = 1 1 0 1
• $b = 0 1 0 1
• ---------------
$c = 1 1 0 1
---------------
• ^ (bitwise XOR) Takes two numbers as operands and does XOR on every bit of two numbers. The result of
XOR is 1 if the two bits are different. For example
$a = 13; // 1101
$b = 5; // 0101
$c = $b ^ $a;
$a = 1 1 0 1
$b = 0 1 0 1
-------------
$c = 1 0 0 0
• ~ (Complement Operator) This is unary operator act as flipping bits. It’s work is to reverse the bits and gives
result using 2’s complement form due to a signed binary number.
(<<) Binary Left Shift Operator will takes two numbers, left shifts the bits of the first operand, the second
operand decides the number of places to shift. It performs multiplication of the left operand by the number of
times specified by the right operand. For Example:
$a = 60;
$c = $a << 2;
print $c;
Output: 240
• Explanation:
• 60 * 2 = 120 ---(1)
$a = 60;
$c = $a >> 2;
print $c;
Output: 15
• Explanation:
• 60 / 2 = 30 ---(1)
• 30 / 2 = 15 ---(2)
Assignment Operators
• Assignment operators are used to assigning a value to a variable. The left side operand of the assignment
operator is a variable and right side operand of the assignment operator is a value.
Different types of assignment operators are shown below:
“=”(Simple Assignment) : This is the simplest assignment operator. This operator is used to assign the
value on the right to the variable on the left.
Example :
• $a = 10;
• $b = 20;
“+=”(Add Assignment) : This operator is combination of ‘+’ and ‘=’ operators. This operator first adds the
current value of the variable on left to the value on the right and then assigns the result to the variable on the
left.
Example : ($a += $b) can be written as ($a = $a + $b)
“-=”(Subtract Assignment) : This operator is combination of ‘-‘ and ‘=’ operators. This operator first
subtracts the current value of the variable on left from the value on the right and then assigns the result to
the variable on the left.
Example : ($a -= $b) can be written as ($a = $a - $b)
“*=”(Multiply Assignment) : This operator is combination of ‘*’ and ‘=’ operators. This operator first
multiplies the current value of the variable on left to the value on the right and then assigns the result to the
variable on the left.
Example : ($a *= $b) can be written as ($a = $a * $b)
“%=”(Modulus Assignment) : This operator is combination of ‘%’ and ‘=’ operators. This operator first
modulo the current value of the variable on left by the value on the right and then assigns the result to the
variable on the left.
Example : ($a %= $b) can be written as ($a = $a % $b)
• It is a conditional operator which is a shorthand version of if-else statement. It has three operands and hence
the name ternary. It will return one of two values depending on the value of a Boolean expression.
Syntax:
Explanation:
• In Perl, range operator is used for creating the specified sequence range of specified
elements.
• This operator is used to create a specified sequence range in which both the starting and
ending element will be inclusive.
For example, 7 .. 10 will create a sequence like 7, 8, 9, 10.
Auto Increment & Auto Decrement Operator
• Auto Increment(++): Increment the value of an integer.
• When placed before the variable name (also called pre-increment operator), its value is incremented instantly.
For example, ++$x.
• when it is placed after the variable name (also called post-increment operator), its value is preserved temporarily
until the execution of this statement and it gets updated before the execution of the next statement.
For example, $x++.
Auto Decrement Operator(--): Decrement the value of an integer.
• When placed before the variable name (also called pre-decrement operator), its value is decremented instantly.
For example, –$x.
• when it is placed after the variable name (also called post-decrement operator), its value is preserved temporarily
until the execution of this statement and it gets updated before the execution of the next statement.
For example, $x–.
Note: The increment and decrement operators are called unary operators as they work with a single operand.
Arrow Operator(->)
• This operator is used for dereferencing a Variable or a Method from a class or an object.
Example: $ob->$x
is an example to access variable $x from object $ob.
Mostly this operator is used as a reference to a hash or an array to access the elements of the
hash or the array.
• The right-hand side of the operator may be an array subscript ([...]), a hash subscript
({...}), or a subroutine argument ((...)). In such cases, the left-hand side must reference an
array, a hash, or a subroutine, respectively.
• For example:
• $ arr->[7] # an array dereference
• The left-hand side of the operator may also reference an object or a class name.
Conditional statements
• Conditional statements are used to decide the flow of execution based on different conditions.
1. if Statement
2. if -else statement
3. if-elsladder
4. unless
5. unless-else
6. unless-elsif
1.Perl If statement
It evaluates the content only if expression is true.
Syntax:
if(expression)
{
//content to be evaluated
}
Note : If the curly brackets { } are not used with if statements then there will
be compile time error. So it is must to use the brackets { } with if statement.
Perl If-else Example
In this example, we'll take input from user by using standard input (<STDIN>/<>).
Perl If else-if Example
• The Perl if else-if statement executes one code from multiple conditions. The syntax of if
else-if statement is given below:
• As soon as one of the conditions controlling the if is true, the statement associated with
that get executed, and the rest of the ladder is bypassed. If none of the conditions is true,
then the final else statement will be executed.
if(condition1)
{
//code to be executed if condition 1is true
}
elsif(condition2){
//code to be executed if condition2 is true }
elsif(condition3){
//code to be executed if condition3 is true }
else{
//code to be executed if all the conditions are false }
Nested – if Statement
• if statement inside an if statement is known as nested if. if statement in this case is the
target of another if or else statement. When more than one condition needs to be true and
one of the condition is the sub-condition of parent condition, nested if can be used.
Syntax :
if (condition1)
{
# Executes when condition1 is true
if (condition2)
{
# Executes when condition2 is true
}
}
# Perl program to illustrate
# Nested if statement
$a = 10;
if($a % 2 ==0)
{
if($a % 5 == 0)
{
printf "Number is divisible by 2 and 5\n";
}
unless Statement
• In this case if the condition is false then the statements
will execute. The number 0, the empty string “”,
character ‘0’, the empty list (), and undef are
all false in a boolean context and all other values are
true.
Syntax :
• Unless(boolean_expression)
{
# will execute if the given condition is false
}
Unless statement program
Unless-else Statement
• Unless statement can be followed by an optional else statement, which executes when the
boolean expression is true.
Syntax :
unless(boolean_expression)
{
# execute if the given condition is false
}
else {
# execute if the given condition is true
}
Unless – elsif Statement
• Unless statement can be followed by an optional elsif…else statement, which is very
useful to test the various conditions using single unless…elsif statement.
Perl given-when Statement
• While loop can execute infinite times which means there is no terminating condition for
this loop.
• In other words, we can say there are some conditions which always remain true, which
causes while loop to execute infinite times or we can say it never terminates.
do…. while loop
• A do..while loop is almost same as a while loop.
• The only difference is that do..while loop runs at least one time.
• The condition is checked after the first execution.
• A do..while loop is used when we want the loop to run at least one time.
• It is also known as exit controlled loop as the condition is checked after executing the
loop.
until loop
• until loop is the opposite of while loop. It takes a condition in the parenthesis and it only
runs until the condition is false. Basically, it repeats an instruction or set of instruction
until the condition is FALSE. It is also entry controller loop i.e. first the condition is
checked then set of instructions inside a block is executed.
for Loop
• “for” loop provides a concise way of writing the loop structure. Unlike a while loop, a
for statement consumes the initialization, condition and increment/decrement in one line
thereby providing a shorter, easy to debug structure of looping.
• Syntax:
foreach Loop
• A foreach loop is used to iterate over a list and the variable holds the value of the
elements of the list one at a time.
• It is majorly used when we have a set of data in a list and we want to iterate over the
elements of the list instead of iterating over its range. The process of iteration of each
element is done automatically by the loop.
Nested Loops