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

SL Unit-III (Perl)

Uploaded by

Priyanka Reddy
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
24 views

SL Unit-III (Perl)

Uploaded by

Priyanka Reddy
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 210

Unit-3

Perl
Practical Extraction and Reporting Language
Introduction to Perl

• Perl is a programming language developed by Larry Wall in 1987.

• Perl is a general-purpose, high level interpreted and dynamic programming language.

• There is no official Full form of the Perl, but still, the most used expansion is “Practical
Extraction and Reporting Language“.

• Perl supports both the procedural and Object-Oriented programming.

• Perl is a lot similar to C syntactically and is easy for the users who have knowledge of C
, C++.
Why Perl?

• Easy to start: Perl is a high-level language so it is closer to other popular programming


languages like C, C++ and thus, becomes easy to learn for anyone.
• Text-Processing: As the acronym “Practical Extraction and Reporting Language” suggest
that Perl has the high text manipulation abilities by which it can generate reports from
different text files easily. Also, it can convert the files into some another form.
• Contained best Features: Perl contains the features of different languages like C,
sed(stream editor), awk(Aho, Weinberger, and Kernighan), and sh etc. which makes the
Perl more useful and productive.
A sh( shell script) is a computer program designed to be run by a Unix shell, a
command-line interpreter.
The AWK language is a data-driven scripting language consisting of a set of actions to

be taken against streams of textual data


• System Administration: Due to having the different scripting languages capabilities Perl
make the task of system administration very easy. Instead of becoming dependent on
many languages, just use Perl to complete out the whole task of system administration. In
Spite of this Perl also used in web programming, web automation, GUI programming etc.

• 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.

• Perl can handle encrypted Web data, including e-commerce transactions.

• Perl's DBI package makes web-database integration easy.

• Perl can be embedded into web servers to speed up processing.


Advantages of Perl:
• Perl Provides supports for cross platform and it is compatible with mark-up languages
like HTML, XML etc.

• It is very efficient in text-manipulation i.e. Regular Expression. It also provides the socket
capability.

• It is free and a Open Source software.

• 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?

Generally, there are two ways to Run a Perl program-


• Using Online IDEs: You can use various online IDEs which can be used to run Perl
programs without installing.

• 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

•First, open a text editor like Notepad or Notepad++.


•Write the code in the text editor and save the file with .pl
extension
•Make sure you have downloaded and installed the latest version
of Perl from https://www.perl.org/get.html
•Open commandline and Run the command perl -v to check if
your Perl’s latest version has been installed properly or not.
• To compile the code type perl HelloWorld.pl. If your code has
no error then it will execute properly and output will be
displayed.
Perl Data Types

• 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.

There are basically three data types in Perl:

• 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:

•integers, simply it’s whole numbers, like 2, 0, 534

•floating-point numbers, it’s real numbers, like 3.14, 6.74, 0.333

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) :

• The concatenation operator “.” unites two or more strings


Conversion Between Numbers and Strings:
Multiline Strings
• If you want to introduce multiline strings into your programs, you can use the standard
single quotes.
Perl Array

• 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):

• It is a set of key-value pair.


• It is also termed the Associative Arrays.
• To declare a hash in Perl, we use the ‘%’ sign.
• To access the particular value, we use the ‘$’ symbol which is followed by the key in
braces.
Perl Variables
• Variables are the reserved memory locations to store values. This means that when you create a
variable you reserve some space in memory.
• Based on the data type of a variable, the interpreter allocates memory and decides what can be
stored in the reserved memory. Therefore, by assigning different data types to variables, you can
store integers, decimals, or strings in these variables.
• Perl uses three types of variables:
1. A scalar variable will precede by a dollar sign ($) and it can store either a number, a
string, or a reference.
2. An array variable will precede by sign @ and it will store ordered lists of scalars.
3. The Hash variable will precede by sign % and will be used to store sets of key/value
pairs.
• Perl maintains every variable type in a separate namespace. So you can, without fear of conflict,
use the same name for a scalar variable, an array, or a hash. This means that $sum and @sum
are two different variables.
Creating Variables
• Perl variables do not have to be explicitly declared to reserve memory space. The
declaration happens automatically when you assign a value to a variable. The equal sign
(=) is used to assign values to variables.
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

• 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.

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

• Variable declared with my scope at the beginning of the script is


accessible through the script including subroutines.
• Variable declared with my scope inside a subroutine is accessible
within that subroutine.
OUTPUT
OUTPUT
Local
• Local variables accessible within block or a subroutine.
• Using this we can actually mask the same variable values to different
values without actually changing the original value of the variable,
suppose we have a variable $a for which the value is assigned 5, you
can actually change the value of that variable by re-declaring the
same variable using local keyword without altering the original value
of the variable which is 5.
OUTPUT
Our
• Once a variable is declared with access modifier “our” it can be used across the entire
package. Suppose, you have Perl module or a package test.pm which has a variable
declared with scope our. This variable can be accessed in any scripts which will use that
package.
use strict
This will help you write better and cleaner code. ‘use strict’ turns on strict pragma
which will make you declare your variables with my keyword.
OUTPUT
OUTPUT
OUTPUT
Quote-like Operators

• 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

• Operators are the main building block of any programming language.


• Operators allow the programmer to perform different kinds of operations on operands.
• In Perl, operators symbols will be different for different kind of operands(like scalars and
string).
• Operators Can be categorized based upon their different functionality:
1. Arithmetic Operators
2.Relational Operators
3.Logical Operators
4.Bitwise Operators
5.Assignment Operators
6.Ternary Operator
Arithmetic Operators: These are used to perform arithmetic/mathematical
operations on operands.
 Addition: ‘+‘ operator is used to add the values of the two operands.

 For Example: $a = 5;

$b = 10;

print $a + $b;

Here Result will be 15

Subtraction: ‘–‘ operator is used to subtract right hand operand from left hand operand.
For Example:

• $a = 10;$b = 5; print $a - $b;

• Here Result will be 5


Multiplication: ‘*‘ operator is used to multiplies the value on either side of the operator.
For Example: $a = 5; $b = 10; print $a * $b;

Here Result will be 50


 Division Operator: ‘/‘ operator returns the remainder when first operand is divided by
the second. For Example: $a = 30; $b = 15; print $a / $b;

Here Result will be 2

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;

Here Result will be 10


 Exponent Operator: ‘**‘ operator is used to perform the exponential(power) calculation on operands.

For Example:

$a = 2;

$b = 3;

print $a**$b;

Here Result will be 8


Relational Operators
• Relational operators are used for comparison of two values.
• These operators will return either 1(true) or nothing(i.e. 0(false)).
• Sometimes these operators are also termed as the Equality Operators.
• These operators have the different symbols to operate on strings.
Equal To Operator: ‘==’ Check if two values are equal or not. If equals then return 1
otherwise return nothing.

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

$c = $b & $a; print $c; Here Output will be 5

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;

print $c; Here Output will be 8

$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)

• 120 * 2 = 240 ---(2)


 (>>)Binary Right Shift Operator will take two numbers, right shifts the bits of the first
operand, the second operand decides the number of places to shift. It performs division
of the left operand by the number of times specified by right operand. For Example:

$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)

If initially value stored in a is 5. Then ($a += 6) = 11.

 “-=”(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)

If initially value stored in a is 8. Then ($a -= 6) = 2.

 “*=”(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)

 If initially value stored in a is 5. Then ($a *= 6) = 30.


 “/=”(Division Assignment) : This operator is combination of ‘/’ and ‘=’ operators. This operator first
divides 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)

If initially value stored in a is 6. Then ($a /= 2) = 3.

 “%=”(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)

If initially value stored in a is 6. Then ($a %= 2) = 0.


 “**=”(Exponent Assignment) : This operator is combination of ‘**’ and ‘=’ operators. This operator first
exponent 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)

If initially, value stored in a is 6. Then ($a **= 2) = 36.


Ternary Operator

• 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:

• condition ? first_expression : second_expression;

Explanation:

• condition: It must be evaluated to true or false.

• If the condition is true

• first_expression is evaluated and becomes the result.

• If the condition is false,

• second_expression is evaluated and becomes the result.


String Manipulation Operators
• String are scalar variables and start with ($) sign in Perl. The String is defined by the user
within a single quote(”) or double quote(“”). There are different types of string operators
in Perl, as follows:
 Concatenation Operator (.) : Perl strings are concatenated with a Dot(.) symbol. The
Dot(.) sign is used instead of (+) sign in Perl.
 Repetition Operator (x): The x operator accepts a string on its left-hand side and a
number on its right-hand side. It will return the string on the left-hand side repeated as
many times as the value on the right-hand side.
Range Operator(..)

• 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

$ hash->{"something"} # a hash dereference

$ subroutine->(1,2) # a subroutine 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

• The Perl if-else statement is used to execute a code if


condition is true or false. The syntax of if-else statement
is given below:
if(expression)
{
//code to be executed if condition is true
}else
{
//code to be executed if condition is false
}
Perl If-else Example with Input from user

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

given-when statement in Perl is a substitute for long if-statements that compare a


variable to several integral values.
•The given-when statement is a multiway branch statement.
•It provides an easy way to dispatch execution to different parts of code
based on the value of the expression.
•given is a control statement that allows a value to change control of execution.
given-when in Perl is similar to the switch-case of C/C++, Python or PHP.
Just like the switch statement, it also substitutes multiple if-statements with different cases.
given-when statements also use two other keywords along with it, namely break and continue.
These keywords maintain the flow of the program and help in getting out of the program execution or
skipping execution at a particular value.
break: break keyword is used to break out of a when block.
In Perl, there is no need to explicitly write the break after every when block. It is already defined
implicitly.
continue: continue, on the other hand, moves to the next when block if first when block is
correct.
Loops in perl
• There may be a situation when you need to execute a block of code several number of
times.
• Perl programming language provides the following types of loop to handle the looping
requirements.
1.while
2.do-while
3.for
4.foreach
5.until
while Loop

• A while loop generally takes an expression in parenthesis.


• If the expression is True then the code within the body of while loop is executed.
• A while loop is used when we don’t know the number of times we want the loop to be
executed however we know the termination condition of the loop.
• It is also known as a entry controlled loop as the condition is checked before executing
the loop. The while loop can be thought of as a repeating if statement.
Infinite While Loop:

• 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

• A nested loop is a loop inside a loop. Nested loops are


also supported by Perl Programming.
• Nested for loop
Nested foreach loop
Nested while loop
Nested do..while loop
Nested until loop
Perl Array

• In Perl, array is a special type of variable. The array is used to store the list of values and
each object of the list is termed as an element. Elements can either be a number, string, or
any type of scalar data including another variable.

Array Creation:
• In Perl programming every array variable is declared using “@” sign before the
variable’s name.

Syntax:
@arrayName = (element1, element2, element3..);
Perl Array Accessing

• To access a single element of a Perl array, use ($) sign before variable name. You can
assume that $ sign represents singular value and @ sign represents plural values.
• Variable name will be followed by square brackets with index number inside it. Indexing
will start with 0 from left side and with -1 from right side.

EX: print "$fruits[0]\n";


Array creation using qw function:
• qw() function is the easiest way to create an array of single-quoted words.
• It takes an expression as an input and extracts the words separated by a whitespace and
then returns a list of those words.
• The best thing is that the expression can be surrounded by any delimiter
like- () ” [] {} // etc. However () and // are used generally.
Syntax:

• qw (Expression)

• qw /Expression/

• qw 'Expression'

• qw {Expression}
Perl Array Size or Length

• Size of an Array: The size of an array(physical size of the array) can be found by
evaluating the array in scalar context. The returned value will be the number of
elements in the array. An array can be evaluated in scalar context using two ways:
1. Implicit Scalar Context

$size = @array;

2. Explicit scalar context using keyword scalar

$size = scalar @array;

@arr = (11, 22, 33, 44, 55, 66);


Perl Array Size or Length
• Note: In Perl arrays, the size of an array is always equal to (maximum_index + 1) i.e.

size = maximum_index + 1

• You can find the maximum index of array by using $#array. So @array and scalar
@array is always used to find the size of an array.
Sequential Number Arrays:

Perl also provides a shortcut to make a sequential array of numbers or letters. It makes out
the user’s task easy. Using sequential number arrays users can skip out loops and typing
each element when counting to 1000 or letters A to Z etc.

• @array = (1..9); # array with numbers from 1 to 9

• @array = (a..h); # array with letters from a to h

Ex:@nums = (1..9);

@letters = (a..h);
Iterating through an Array:

• We can iterate in an array using two ways:


1. Iterating through the range
2.Iterating through elements(foreach Loop)
1. Iterating through the range:
We can iterate through the range by finding the size of an array and then running a for
loop from 0 to the size – 1 and then accessing the elements of the array.

2.Iterating through elements(foreach Loop):


• We can iterate through the elements using foreach loop.
• Using this we can directly access the elements of the array using a loop instead of
running a loop over its range and then accessing the elements.
Iterating through the range:
Iterating through elements(foreach Loop)
Perl Array Functions

• You can add or remove an element from an array using some array functions.

1.Push

2.Pop

3.Shift

4.Unshift
1.Push on Array

• The push array function appends a new element at the end of the array.
Syntax: push(@<arrayname>,<element>)
2. Pop on Array

• The pop array function removes the last element from the array.
Syntax: pop(@<arrayname>);
3 Shift on Array

• The shift array function removes the left most element of array and thus shorten the array
by 1.
Syntax: shift(<@arrayname>)
4.Unshift on Array

• The unshift array function adds a new element at the start of the array.
Syntax: unshift(@<arrayname>,<element>);
Perl Replacing Array Elements, splice()

• The splice array function removes the elements as defined and replaces them with the
given list.
Syntax: splice(@array, offset, length, replacement_list)
Perl Strings to Arrays, split()
• With the help of split() function, we can split a string into array of strings and returns it.
Syntax: spilt(“delimiter”,<string variable>);
Perl Arrays to Strings, join()

• This join() function is used to combine arrays to make a string. It combines the separate
arrays into one string and returns it.
Syntax: join(VAR, LIST)
• VAR : Separator to be placed between list elements.
• LIST : LIST to be converted into String.
Perl Merging Two Arrays, merged()
• Two arrays can be merged together using merged() function as a single string removing
all the commas in between them.
Syntax: (@<array1>,@<array2>);
Perl Sorting Arrays, sort()
• To sort an array, sort() array function is used. The sort() function sorts all the elements of
an array according to the ASCII standard.
Syntax: sort(@<arrayname>);
Perl String

• A string in Perl is a scalar variable and start with a ($) sign and it can
contain alphabets, numbers, special characters.
• The string can consist of a single word, a group of words or a multi-
line paragraph.
• The String is defined by the user within a single quote (‘) or double
quote (“).
Perl also allows you to use quote-like operators such as:
•The q// acts like a single-quoted string.
•The qq// acts like double-quoted string.
String Declaration and Initialization in Perl

Since Strings are scalars, their name starts with $


For example:
String interpolation – Single vs double quotes

double quotes interpolated escape sequences “\t” and “\n” however single quotes did
not.
String Manipulation Operators
• String are scalar variables and start with ($) sign in Perl. The String is defined by the user
within a single quote(”) or double quote(“”). There are different types of string operators
in Perl, as follows:
 Concatenation Operator (.) : Perl strings are concatenated with a Dot(.) symbol. The
Dot(.) sign is used instead of (+) sign in Perl.
 Repetition Operator (x): The x operator accepts a string on its left-hand side and a
number on its right-hand side. It will return the string on the left-hand side repeated as
many times as the value on the right-hand side.
Perl string functions

• Perl provides a set of functions that allow you to manipulate strings effectively.
Perl string length
• To find the number of characters in a string, you use the length() function. See the
following example:
Ex:
my $s = "This is a string\n";
print(length($s),"\n");
Output: 17
Changing cases of string

• To change the cases of a string you use a pair of functions lc() and
uc() that returns the lowercase and uppercase versions of a string.
substr() function

• Returns a substring out of the string passed to the function starting from a given index up
to the length specified.
• This function by default returns the remaining part of the string starting from the given
index if the length is not specified.
• A replacement string can also be passed to the substr() function if you want to replace that
part of the string with some other substring.
• This index and length value might be negative as well which changes the direction of
index count in the string.
Syntax: substr(string, index, length, replacement)
Parameters: string: string from which substring is to be extracted
index: starting index of the substring
length: length of the substring
replacement: replacement substring(if any)
Returns: the substring of the required length
chomp() Function

• The chomp() function in Perl is used to remove the last trailing newline from the input
string.
syntax: chomp(String)
• Parameters:
String : Input String whose trailing newline is to be removed
• Returns: the total number of trailing newlines removed from all its arguments
chop() Function

The chop() function in Perl is used to remove the last character from the input string.
Syntax: chop(String)
Parameters: String : It is the input string whose last characters are removed.
Returns: the last removed character.
index() Function

• This function returns the position of the first occurrence of given substring (or pattern) in
a string (or text).
• We can specify start position. By default, it searches from the beginning(i.e. from index
zero).
Syntax:
# Searches pattern in text from given index
index(text, pattern, index)
• # Searches pattern in text
index(text, pattern)
Parameters:
• text: String in which substring is to be searched.
• pattern: Substring to be searched.
• index: Starting index(set by the user or it takes zero by default).
• Returns: -1 on failure otherwise Position of the matching string.
perl
rindex() Function
rindex() function in Perl operates similar to index() function,
except it returns the position of the last occurrence of the substring (or pattern) in the string (or text).
If the position is specified, returns the last occurrence at or before that position.
Syntax:
# Searches pattern in text from given Position
rindex( text, pattern, Position)
# Searches pattern in text
rindex (text, pattern)
Parameters:
• text: String in which substring is to be searched.
• pattern: Substring to be searched.
• index: Starting index(set by the user or it takes zero by default).
• Returns:
-1 on failure otherwise position of last occurrence.
split()
split() is a string function in Perl which is used to split( or) cut a string into smaller sections or
pieces.
There are different criteria to split a string, like on a single character, a regular
expression(pattern), a group of characters or on undefined value etc..
The best thing about this function that user can specify how many sections to split the string into.
Syntax:
split (/Pattern/, Expression, Limit)
Or
split (/Pattern/, Expression)
Or
Split (/Pattern/)
Or
Split ()
Perl - Hashes
• 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 preceded by a
"$" sign and followed by the "key" associated with the value in curly brackets.
Creating Hashes

Hashes are created in one of the following ways.


• In the first method, you assign a value to a named key on a one-by-one basis.
$data{'John Paul'} = 45;
$data{'Lisa'} = 30;
$data{'Kumar'} = 40;
• In the second case, you use a list, which is converted by taking individual pairs from the
list: the first element of the pair is used as the key, and the second, as the value.
%data = ('John Paul', 45, 'Lisa', 30, 'Kumar', 40);
• => as an alias , to indicate the key/value pairs as follows −

%data = ('John Paul' => 45, 'Lisa' => 30, 'Kumar' => 40);

%data = (-JohnPaul => 45, -Lisa => 30, -Kumar => 40);
Accessing Hash Elements

• When accessing individual elements from a hash, you must prefix the
variable with a dollar sign ($) and then append the element key within
curly brackets after the name of the variable.
Extracting Slices

• Extract slices of a hash just as you can extract slices from an array.
• You will need to use @ prefix for the variable to store the returned value because
they will be a list of values .
Extracting Keys and Values
• You can get a list of all of the keys from a hash by using keys function,
which has the following
syntax
keys %HASH
• This function returns an array of all the keys of the named hash.
• Similarly, you can use values function to get a list of all the values. This
function has the following
syntax
values %HASH
• This function returns a normal array consisting of all the values of the
named hash.
Extracting Keys and Values
Extracting Values
Checking for Existence
• Accessing a key-value pair from hash which doesn't exist will return error or warnings. To
prevent from this, you can check whether a key exist or not in a hash with exists()
function. It returns true if the key exists.
Hash Size
• You can get the size - that is, the number of elements from a hash by using the scalar
context on either keys or values. Simply saying first you have to get an array of either the
keys or values and then you can get the size of array.
Add and Remove Elements in Hashes
• Adding a new key/value pair can be done with one line of code using simple assignment
operator. But to remove an element from the hash you need to use delete function.
Perl Hash creating Empty hash

• An empty hash will always have size 0.


Perl List and its Types
• A list is a collection of scalar values.
• We can access the elements of a list using indexes.
• Index starts with 0 (0th index refers to the first element of the list).
• We use parenthesis and comma operators to construct a list.
• In Perl, scalar variables start with a $ symbol whereas list variables start with @ symbol.
• Lists are of multiple types
Simple Lists: A list with same datatypes is referred to as a Simple List
Complex Lists: A list may contain various different datatypes. These type of
lists are referred to as Complex Lists.
Flattening List: A list may contain another list within it but Perl will flatten the
internal list and the elements of this list will be treated as the
elements of the outer list.
Simple list
Complex Lists
Flattening list
Accessing List Elements

• List elements can be accessed with the use of a scalar variable. While accessing a
List element, $ is used, because a scalar variable in Perl is accessed with the use
of $ symbol.
Slicing a List

• Slicing a list in Perl can be done by giving comma(,) separated index values to another
list.
Defining Range in a List
Range operator in Perl is used as a short way to create a list.
When used with list, the range operator simplifies the process of creating
a list with contiguous sequences of numbers and letters.
The range operator can also be used for slicing the list.
Syntax: leftValue..rightValue
Pattern Matching
• A pattern is a sequence of characters to be searched for in a character string. In Perl,
patterns are normally enclosed in slash characters:
/def/ This represents the pattern def.
The Match Operators(=~ and !~)
• Perl defines special operators that test whether a particular pattern appears in a character
string.
• The =~ operator tests whether a pattern is matched
Ex: $result = $var =~ /abc/; The result of the =~ operation is one of the
following:
A nonzero value, or true, if the pattern is found in the string
0, or false, if the pattern is not matched
• the value stored in the scalar variable $var is searched for the pattern abc. If abc is
found, $result is assigned a nonzero value; otherwise, $result is set to zero.
• The !~ operator is similar to =~, except that it checks whether a pattern is not matched.
EX: $result = $var !~ /abc/;
Here, $result is set to 0 if abc appears in the string assigned to $var, and to a nonzero
value if abc is not found.
• Because =~ and !~ produce either true or false as their result, these operators are ideally
suited for use in conditional expressions.
Perl Matching Operator !~
It is the opposite of =~ operator
Regular Expressions in Perl
Regular Expression

• A Regular Expression (or Regex) is a pattern (or filter) that describes a set of strings that
matches the pattern.

• Perl makes extensive use of regular expressions with many built-in syntaxes and
operators.

• In Perl a regex is delimited by a pair of forward slashes (default), in the form of /regex/.
• The basic method for applying a regular expression is to use the pattern binding operators
=~ and !~. The first operator is a test and assignment operator.

• There are three regular expression operators inside perl:


Matching regular expression operator
Substitute regular expression operator
Transliterate regular expression operator
Matching Operator m//

• we can use matching operator m// to check if a regex pattern exists


in a string. The syntax is:
1. m/regex/
2. m/regex/modifiers # Optional modifiers
3. /regex/ # Operator m can be omitted if forward-

slashes are used as delimiter


4. /regex/modifiers
Matching Operator m//

• Instead of using forward-slashes (/) as delimiter, you could use other non-
alphanumeric characters such as !, @ and %
Eg:
m!regex!modifiers
m@regex@modifiers or
m%regex%modifiers.
• If forward-slash (/) is used as the delimiter, the operator m can be omitted in the
form of
/regex/modifiers
• m//, by default, operates on the default variable $_.
• It returns true if $_ matches regex and false otherwise.
Perl Matching Operator with $_
a special default variable $_.
Regular Expression Variables
• Regular expression variables include $, which contains whatever the last grouping
match matched;
• $& which contains the entire matched string
• $` which contains everything before the matched string
• $’ which contains everything after the matched string.
Operators =~ and !~
By default, the matching operators operate on the default variable $_.
To operate on other variable instead of $_,
you could use the =~ and !~ operators as follows:

str =~ m/regex/modifiers # Return true if str matches regex.


str !~ m/regex/modifiers # Return true if str does NOT match regex.

When used with m//, =~ behaves like comparison (== or eq).


Perl Matching Operator !~
It is the opposite of =~ operator
Substitution Operator s///

You can substitute a string (or a portion of a string) with another string using s/// substitution operator.
The syntax is:
s/regex/replacement/
s/regex/replacement/modifiers # Optional modifiers.
Similar to m//, s/// operates on the default variable $_ by default.
To operate on other variable, you could use the =~ and !~ operators.
When used with s///, =~ behaves like assignment (=).
Character Translation Operator tr///

Translator operator is used to translate a character into another character.


The syntax is:

tr/fromchars/tochars/modifiers

replaces or translates fromchars to tochars in $_, and returns the number of characters
replaced.
Perl Translation Operator replacing more than one letter
Perl quantifiers
Uses of Regular Expression:

• It can be used to count the number of occurrence of a specified pattern in a string.

• It can be used to search for a string which matches the specified pattern.

• It can also replace the searched pattern with some other specified string.
Built in functions in PERL:

chr() Function:
The chr() function in Perl returns a string representing a character whose
Unicode code point is an integer.
• Syntax:

chr(Num) ;

Parameters:

Num : It is an Unicode integer value whose corresponding character is returned .

Returns: a string representing a character whose Unicode code point is an integer.


sleep() Function

• sleep() function in Perl is an inbuilt function which is used to delay


the execution of the current script for a specified number of seconds
or forever if parameter is not specified.
• The sleep( ) function accepts seconds as a parameter and returns the
same on success.
Syntax: sleep(seconds)
Returns: seconds passed to it as parameter, on success
Example 1:
print scalar localtime();
# calling the sleep function
sleep(5);
print "\n";
print scalar localtime();
ord() Function

The ord() function is an inbuilt function in Perl that returns the ASCII value of the first character of a string.
This function takes a character string as a parameter and returns the ASCII value of the first character of this
string.
Syntax: ord string
• Parameter: This function accepts a single parameter ‘string’ from which we can get an ASCII value.
• Returns: an integer value which represents the ASCII value of the first character in the string passed to this
function as a parameter.
• Examples:
Input:ord( “WelcometoGFG” )
Output: 87
• Explanation: The ASCII value of W is 87
return() Function

return() function in Perl returns Value at the end of a subroutine,


block, or do function.
Returned value might be scalar, array, or a hash according to the
selected context.
Syntax: return Value
Returns: a List in Scalar Context
Note: If no value is passed to the return function then it returns an
empty list in the list context, undef in the scalar context and nothing
in void context.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy