SlideShare a Scribd company logo
PERL PROGRAMMING
LANGUAGE
CC103 SURVEY OF CURRENT MULTI-PARADIGM PROGRAMMING LANGUAGES
PERL SYNTAX OVERVIEW
• Perl borrows syntax and concepts from many languages: awk, sed, C, Bourne Shell, Smalltalk,
Lisp and even English. However, there are some definite differences between the languages. This
chapter is designd to quickly get you up to speed on the syntax that is expected in Perl.
• A Perl program consists of a sequence of declarations and statements, which run from the top
to the bottom. Loops, subroutines, and other control structures allow you to jump around within
the code. Every simple statement must end with a semicolon (;).
• Perl is a free-form language: you can format and indent it however you like. Whitespace serves
mostly to separate tokens, unlike languages like Python where it is an important part of the
syntax, or Fortran where it is immaterial.
PERL DATA TYPES
• Perl is a loosely typed language and there is no need to specify a type for your data while using
in your program. The Perl interpreter will choose the type based on the context of the data itself.
• Perl has three basic data types: scalars, arrays of scalars, and hashes of scalars, also known as
associative arrays. Here is a little detail about these data types.
Sr.No. Types & 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 NUMERIC LITERALS
• Perl stores all the numbers internally as either signed integers or double-precision floating-point
values. Numeric literals are specified in any of the following floating-point or integer formats −
Type Value
Integer 1234
Negative integer -100
Floating point 2000
Scientific notation 16.12E14
Hexadecimal 0xffff
Octal 0577
PERL STRING LITERALS
• Strings are sequences of characters. They are usually alphanumeric values delimited by either
single (') or double (") quotes. They work much like UNIX shell quotes where you can use single
quoted strings and double quoted strings.
• Double-quoted string literals allow variable interpolation, and single-quoted strings are not.
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).
• You can embed newlines or any of the following Escape sequences directly in your double
quoted strings −
Escape sequence Meaning
 Backslash
' Single quote
" Double quote
a Alert or bell
b Backspace
f Form feed
n Newline
r Carriage return
t Horizontal tab
v Vertical tab
0nn Creates Octal formatted numbers
xnn Creates Hexideciamal formatted numbers
cX Controls characters, x may be any
character
u Forces next character to uppercase
l Forces next character to lowercase
U Forces all following characters to
uppercase
PERL STRING EXAMPLES
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.
• We have learnt that Perl has the following three basic data types −
• Scalars
• Arrays
• Hashes
• Accordingly, we are going to use three types of variables in Perl. A scalar variable will precede
by a dollar sign ($) and it can store either a number, a string, or a reference. An array variable
will precede by sign @ and it will store ordered lists of scalars. Finally, 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 $foo and
@foo are two different variables.
PERL VARIABLES
String 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.
• Keep a note that this is mandatory to declare a variable before we use it if we 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 Paul"; # A string
• $salary = 1445.50; # A floating point
• Here 25, "John Paul" and 1445.50 are the values assigned to $age, $name and $salary
variables, respectively. Shortly we will see how we can assign values to arrays and
hashes.
PERL 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.
Here is a simple example of using scalar variables −
PERL VARIABLES
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.
Here is a simple example of using array variables −
Here we used escape sign () before the $ sign just to print it. Other Perl will understand
it as a variable and will print its value. When executed, this will produce the following
result −
PERL VARIABLES
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.
Here is a simple example of using hash variables −
PERL VARIABLES
Variable Context
Perl treats same variable differently based on Context, i.e., situation where
a variable is being used. Let's check the following example −
PERL VARIABLES
Here @names is an array, which has been used in two different contexts.
First we copied it into anyother array, i.e., list, so it returned all the
elements assuming that context is list context. Next we used the same
array and tried to store this array in a scalar, so in this case it returned just
the number of elements in this array assuming that context is scalar
context. Following table lists down the various contexts −
Sr.No. Context & 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 Boolean
Boolean context is simply any place where an expression is being evaluated to see
whether it's true or false.
4 Void
This context not only doesn't care what the return value is, it doesn't even want a return
value.
PERL SCALARS
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.
Here is a simple example of using scalar variables −
PERL SCALARS
NUMERIC SCALAR
A scalar is most often either a number or a string. Following example
demonstrates the usage of various types of numeric scalars −
PERL SCALARS
String Scalars
Following example demonstrates the usage of various types of string
scalars. Notice the difference between single quoted strings and double
quoted strings −
PERL SCALARS
Scalar Operations
You will see a detail of various operators available in Perl in a separate chapter, but here
we are going to list down few numeric and string operations.
PERL SCALARS
Multiline Strings
If you want to introduce multiline strings into your programs, you can use
the standard single quotes as below −
PERL ARRAYS
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.
Here is a simple example of using the array variables −
PERL ARRAYS
Here we have used the escape sign () before the $ sign just to print it.
Other Perl will understand it as a variable and will print its value. When
executed, this will produce the following result −
In Perl, List and Array terms are often used as if they're interchangeable. But the list is
the data, and the array is the variable.
PERL ARRAYS
Array Creation
Array variables are prefixed with the @ sign and are populated using
either parentheses or the qw operator. For example −
The second line uses the qw// operator, which returns a list of strings, separating the
delimited string by white space. In this example, this leads to a four-element array; the
first element is 'this' and last (fourth) is 'array'. This means that you can use different
lines as follows −
PERL ARRAYS
Array Creation
You can also populate an array by assigning each value individually as follows −
Accessing Array Elements
When accessing individual elements from an array, you must prefix the variable with a
dollar sign ($) and then append the element index within the square brackets after the
name of the variable. For example −
PERL ARRAYS
Array Creation
Array indices start from zero, so to access the first element you need to give 0 as indices.
You can also give a negative index, in which case you select the element from the end,
rather than the beginning, of the array. This means the following −
PERL IF ELSE (CONDITIONAL STATEMENTS)
Perl conditional statements helps in the decision making, which require
that the programmer specifies one or more conditions to be evaluated or
tested by the program, along with a statement or statements to be
executed if the condition is determined to be true, and optionally, other
statements to be executed if the condition is determined to be false.
Following is the general from of a typical decision making structure found
in most of the programming languages −
PERL IF ELSE (CONDITIONAL STATEMENTS)
The ? : Operator
Let's check the conditional operator ? :which can be used to replace
if...else statements. It has the following general form −
Exp1 ? Exp2 : Exp3;
Where Exp1, Exp2, and Exp3 are expressions. Notice the use and
placement of the colon.
The value of a ? expression is determined like this: Exp1 is evaluated. If it
is true, then Exp2 is evaluated and becomes the value of the entire ?
expression. If Exp1 is false, then Exp3 is evaluated and its value becomes
the value of the expression. Below is a simple example making use of this
operator −
PERL IF ELSE (CONDITIONAL STATEMENTS)
PERL LOOPS
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.
A loop statement allows us to execute a statement or
group of statements multiple times and following is
the general form of a loop statement in most of the
programming languages
Perl programming language provides the following
types of loop to handle the looping requirements.
PERL LOOPS
Loop Control Statements
Loop control statements change the
execution from its normal sequence. When
execution leaves a scope, all automatic
objects that were created in that scope are
destroyed.
Perl supports the following control
statements
1. next statement
Causes the loop to skip the remainder of its body
and immediately retest its condition prior to
reiterating.
2. last statement
Terminates the loop statement and transfers
execution to the statement immediately following
the loop.
3. continue statement
A continue BLOCK, it is always executed just
before the conditional is about to be evaluated
again.
4. redo statement
The redo command restarts the loop block
without evaluating the conditional again. The
continue block, if any, is not executed.
5. goto statement
Perl supports a goto command with three forms:
PERL IF ELSE (CONDITIONAL STATEMENTS)
• The Infinite Loop
• A loop becomes infinite loop if a condition never becomes false. The for loop is traditionally used
for this purpose. Since none of the three expressions that form the for loop are required, you
can make an endless loop by leaving the conditional expression empty.
PERL OPERATORS
• What is an Operator?
• 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, but following is
a list of important and most frequently used operators −
• Arithmetic Operators
• Equality Operators
• Logical Operators
• Assignment Operators
• Bitwise Operators
• Logical Operators
• Quote-like Operators
• Miscellaneous Operators
PERL OPERATORS
• Perl Arithmetic Operators
Assume variable $a holds 10 and variable $b holds 20, then following are the Perl
arithmatic operators −
Sr.No. Operator & Description
1 + ( Addition )
Adds values on either side of the operator Example $a + $b will give 30
−
2 - (Subtraction)
Subtracts right hand operand from left hand operand Example $a - $b will give -10
−
3 * (Multiplication)
Multiplies values on either side of the operatorExample $a * $b will give 200
−
4 / (Division)
Divides left hand operand by right hand operand Example $b / $a will give 2
−
5 % (Modulus)
Divides left hand operand by right hand operand and returns remainder Example −
$b % $a will give 0
6 ** (Exponent)
Performs exponential (power) calculation on operators Example $a**$b will give
−
PERL OPERATORS
• Perl Equality Operators
• These are also called relational operators. Assume variable $a holds 10 and variable $b holds 20
then, lets check the following numeric equality operators −
Sr.No. Operator & Description
1 == (equal to)
Checks if the value of two operands are equal or not, if yes then condition becomes true.
Example ($a == $b) is not true.
−
2 != (not equal to)
Checks if the value of two operands are equal or not, if values are not equal then condition becomes true.
Example ($a != $b) is true.
−
3 <=>
Checks if the value of two operands are equal or not, and returns -1, 0, or 1 depending on whether the left argument is
numerically less than, equal to, or greater than the right argument.
Example ($a <=> $b) returns -1.
−
4 > (greater than)
Checks if the value of left operand is greater than the value of right operand, if yes then condition becomes true.
Example ($a > $b) is not true.
−
5 < (less than)
Checks if the value of left operand is less than the value of right operand, if yes then condition becomes true.
Example ($a < $b) is true.
−
6 >= (greater than or equal to)
Checks if the value of left operand is greater than or equal to the value of right operand, if yes then condition becomes true.
Example ($a >= $b) is not true.
−
7 <= (less than or equal to)
PERL OPERATORS
• Perl Assignment Operators
• Assume variable $a holds 10 and variable $b holds 20, then below are the assignment operators
available in Perl and their usage −
Sr.No. Operator & Description
1 =
Simple assignment operator, Assigns values from right side operands to left side operand
Example $c = $a + $b will assigned value of $a + $b into $c
−
2 +=
Add AND assignment operator, It adds right operand to the left operand and assign the result to left operand
Example $c += $a is equivalent to $c = $c + $a
−
3 -=
Subtract AND assignment operator, It subtracts right operand from the left operand and assign the result to left operand
Example $c -= $a is equivalent to $c = $c - $a
−
4 *=
Multiply AND assignment operator, It multiplies right operand with the left operand and assign the result to left operand
Example $c *= $a is equivalent to $c = $c * $a
−
5 /=
Divide AND assignment operator, It divides left operand with the right operand and assign the result to left operand
Example $c /= $a is equivalent to $c = $c / $a
−
6 %=
Modulus AND assignment operator, It takes modulus using two operands and assign the result to left operand
Example $c %= $a is equivalent to $c = $c % a
−
7 **=
PERL OPERATORS
• Perl Logical Operators
• There are following logical operators supported by Perl language. Assume variable $a holds true
and variable $b holds false then −
Sr.No. Operator & Description
1 and
Called Logical AND operator. If both the operands are true then then condition becomes true.
Example ($a and $b) is false.
−
2 &&
C-style Logical AND operator copies a bit to the result if it exists in both operands.
Example ($a && $b) is false.
−
3 or
Called Logical OR Operator. If any of the two operands are non zero then then condition becomes
true.
Example ($a or $b) is true.
−
4 ||
C-style Logical OR operator copies a bit if it exists in eather operand.
Example ($a || $b) is true.
−
5 not
PERL OPERATORS
• Miscellaneous Operators
• There are following miscellaneous operators supported by Perl language. Assume variable a
holds 10 and variable b holds 20 then −
Sr.No. Operator & Description
1 .
Binary operator dot (.) concatenates two strings.
Example If $a = "abc", $b = "def" then $a.$b will give "abcdef"
−
2 x
The repetition operator x returns a string consisting of the left operand repeated the number of times specified by the right
operand.
Example ('-' x 3) will give ---.
−
3 ..
The range operator .. returns a list of values counting (up by ones) from the left value to the right value
Example (2..5) will give (2, 3, 4, 5)
−
4 ++
Auto Increment operator increases integer value by one
Example $a++ will give 11
−
5 --
Auto Decrement operator decreases integer value by one
Example $a-- will give 9
−
6 ->
The arrow operator is mostly used in dereferencing a method or variable from an object or a class name

More Related Content

Similar to PERL PROGRAMMING LANGUAGE Basic Introduction (20)

DOC
9
satishbb
 
PPTX
PERL_History_Concepts_Scalar_Syntax_Example.pptx
spkrishna4u
 
PDF
Perl programming language
Elie Obeid
 
PDF
Perl_Part1
Frank Booth
 
PDF
7-Java Language Basics Part1
Amr Elghadban (AmrAngry)
 
PPTX
Complete Overview about PERL
Ravi kumar
 
PPT
Introduction to perl_lists
Vamshi Santhapuri
 
PPTX
Unit 1-array,lists and hashes
sana mateen
 
PDF
Maxbox starter20
Max Kleiner
 
PPT
Introduction to perl scripting______.ppt
nalinisamineni
 
PPTX
Unit 1-subroutines in perl
sana mateen
 
PPTX
Subroutines in perl
sana mateen
 
PPT
PERL - complete_guide_references (1).ppt
ssuserf4000e1
 
PPT
PERL - complete_Training_Modules_Ref.ppt
ssuserf4000e1
 
PPT
Perl Basics with Examples
Nithin Kumar Singani
 
PDF
RegexCat
Kyle Hamilton
 
PDF
Perl_Part6
Frank Booth
 
PDF
Perl_Part4
Frank Booth
 
PPT
PERL Regular Expression
Binsent Ribera
 
PERL_History_Concepts_Scalar_Syntax_Example.pptx
spkrishna4u
 
Perl programming language
Elie Obeid
 
Perl_Part1
Frank Booth
 
7-Java Language Basics Part1
Amr Elghadban (AmrAngry)
 
Complete Overview about PERL
Ravi kumar
 
Introduction to perl_lists
Vamshi Santhapuri
 
Unit 1-array,lists and hashes
sana mateen
 
Maxbox starter20
Max Kleiner
 
Introduction to perl scripting______.ppt
nalinisamineni
 
Unit 1-subroutines in perl
sana mateen
 
Subroutines in perl
sana mateen
 
PERL - complete_guide_references (1).ppt
ssuserf4000e1
 
PERL - complete_Training_Modules_Ref.ppt
ssuserf4000e1
 
Perl Basics with Examples
Nithin Kumar Singani
 
RegexCat
Kyle Hamilton
 
Perl_Part6
Frank Booth
 
Perl_Part4
Frank Booth
 
PERL Regular Expression
Binsent Ribera
 

Recently uploaded (20)

PDF
“Voice Interfaces on a Budget: Building Real-time Speech Recognition on Low-c...
Edge AI and Vision Alliance
 
PDF
How do you fast track Agentic automation use cases discovery?
DianaGray10
 
PDF
"Beyond English: Navigating the Challenges of Building a Ukrainian-language R...
Fwdays
 
PPTX
OpenID AuthZEN - Analyst Briefing July 2025
David Brossard
 
PDF
Staying Human in a Machine- Accelerated World
Catalin Jora
 
PDF
Mastering Financial Management in Direct Selling
Epixel MLM Software
 
PDF
CIFDAQ Market Wrap for the week of 4th July 2025
CIFDAQ
 
PPTX
Designing_the_Future_AI_Driven_Product_Experiences_Across_Devices.pptx
presentifyai
 
PDF
Transcript: New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
PDF
"AI Transformation: Directions and Challenges", Pavlo Shaternik
Fwdays
 
PPTX
Mastering ODC + Okta Configuration - Chennai OSUG
HathiMaryA
 
PDF
Automating Feature Enrichment and Station Creation in Natural Gas Utility Net...
Safe Software
 
PDF
Transcript: Book industry state of the nation 2025 - Tech Forum 2025
BookNet Canada
 
PPTX
AI Penetration Testing Essentials: A Cybersecurity Guide for 2025
defencerabbit Team
 
PDF
Go Concurrency Real-World Patterns, Pitfalls, and Playground Battles.pdf
Emily Achieng
 
PPTX
COMPARISON OF RASTER ANALYSIS TOOLS OF QGIS AND ARCGIS
Sharanya Sarkar
 
PDF
Newgen 2022-Forrester Newgen TEI_13 05 2022-The-Total-Economic-Impact-Newgen-...
darshakparmar
 
PPTX
Q2 FY26 Tableau User Group Leader Quarterly Call
lward7
 
PDF
Newgen Beyond Frankenstein_Build vs Buy_Digital_version.pdf
darshakparmar
 
PDF
The 2025 InfraRed Report - Redpoint Ventures
Razin Mustafiz
 
“Voice Interfaces on a Budget: Building Real-time Speech Recognition on Low-c...
Edge AI and Vision Alliance
 
How do you fast track Agentic automation use cases discovery?
DianaGray10
 
"Beyond English: Navigating the Challenges of Building a Ukrainian-language R...
Fwdays
 
OpenID AuthZEN - Analyst Briefing July 2025
David Brossard
 
Staying Human in a Machine- Accelerated World
Catalin Jora
 
Mastering Financial Management in Direct Selling
Epixel MLM Software
 
CIFDAQ Market Wrap for the week of 4th July 2025
CIFDAQ
 
Designing_the_Future_AI_Driven_Product_Experiences_Across_Devices.pptx
presentifyai
 
Transcript: New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
"AI Transformation: Directions and Challenges", Pavlo Shaternik
Fwdays
 
Mastering ODC + Okta Configuration - Chennai OSUG
HathiMaryA
 
Automating Feature Enrichment and Station Creation in Natural Gas Utility Net...
Safe Software
 
Transcript: Book industry state of the nation 2025 - Tech Forum 2025
BookNet Canada
 
AI Penetration Testing Essentials: A Cybersecurity Guide for 2025
defencerabbit Team
 
Go Concurrency Real-World Patterns, Pitfalls, and Playground Battles.pdf
Emily Achieng
 
COMPARISON OF RASTER ANALYSIS TOOLS OF QGIS AND ARCGIS
Sharanya Sarkar
 
Newgen 2022-Forrester Newgen TEI_13 05 2022-The-Total-Economic-Impact-Newgen-...
darshakparmar
 
Q2 FY26 Tableau User Group Leader Quarterly Call
lward7
 
Newgen Beyond Frankenstein_Build vs Buy_Digital_version.pdf
darshakparmar
 
The 2025 InfraRed Report - Redpoint Ventures
Razin Mustafiz
 
Ad

PERL PROGRAMMING LANGUAGE Basic Introduction

  • 1. PERL PROGRAMMING LANGUAGE CC103 SURVEY OF CURRENT MULTI-PARADIGM PROGRAMMING LANGUAGES
  • 2. PERL SYNTAX OVERVIEW • Perl borrows syntax and concepts from many languages: awk, sed, C, Bourne Shell, Smalltalk, Lisp and even English. However, there are some definite differences between the languages. This chapter is designd to quickly get you up to speed on the syntax that is expected in Perl. • A Perl program consists of a sequence of declarations and statements, which run from the top to the bottom. Loops, subroutines, and other control structures allow you to jump around within the code. Every simple statement must end with a semicolon (;). • Perl is a free-form language: you can format and indent it however you like. Whitespace serves mostly to separate tokens, unlike languages like Python where it is an important part of the syntax, or Fortran where it is immaterial.
  • 3. PERL DATA TYPES • Perl is a loosely typed language and there is no need to specify a type for your data while using in your program. The Perl interpreter will choose the type based on the context of the data itself. • Perl has three basic data types: scalars, arrays of scalars, and hashes of scalars, also known as associative arrays. Here is a little detail about these data types. Sr.No. Types & 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 (%).
  • 4. PERL NUMERIC LITERALS • Perl stores all the numbers internally as either signed integers or double-precision floating-point values. Numeric literals are specified in any of the following floating-point or integer formats − Type Value Integer 1234 Negative integer -100 Floating point 2000 Scientific notation 16.12E14 Hexadecimal 0xffff Octal 0577
  • 5. PERL STRING LITERALS • Strings are sequences of characters. They are usually alphanumeric values delimited by either single (') or double (") quotes. They work much like UNIX shell quotes where you can use single quoted strings and double quoted strings. • Double-quoted string literals allow variable interpolation, and single-quoted strings are not. 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). • You can embed newlines or any of the following Escape sequences directly in your double quoted strings − Escape sequence Meaning Backslash ' Single quote " Double quote a Alert or bell b Backspace f Form feed n Newline r Carriage return t Horizontal tab v Vertical tab 0nn Creates Octal formatted numbers xnn Creates Hexideciamal formatted numbers cX Controls characters, x may be any character u Forces next character to uppercase l Forces next character to lowercase U Forces all following characters to uppercase
  • 7. 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. • We have learnt that Perl has the following three basic data types − • Scalars • Arrays • Hashes • Accordingly, we are going to use three types of variables in Perl. A scalar variable will precede by a dollar sign ($) and it can store either a number, a string, or a reference. An array variable will precede by sign @ and it will store ordered lists of scalars. Finally, 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 $foo and @foo are two different variables.
  • 8. PERL VARIABLES String 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. • Keep a note that this is mandatory to declare a variable before we use it if we 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 Paul"; # A string • $salary = 1445.50; # A floating point • Here 25, "John Paul" and 1445.50 are the values assigned to $age, $name and $salary variables, respectively. Shortly we will see how we can assign values to arrays and hashes.
  • 9. PERL 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. Here is a simple example of using scalar variables −
  • 10. PERL VARIABLES 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. Here is a simple example of using array variables − Here we used escape sign () before the $ sign just to print it. Other Perl will understand it as a variable and will print its value. When executed, this will produce the following result −
  • 11. PERL VARIABLES 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. Here is a simple example of using hash variables −
  • 12. PERL VARIABLES Variable Context Perl treats same variable differently based on Context, i.e., situation where a variable is being used. Let's check the following example −
  • 13. PERL VARIABLES Here @names is an array, which has been used in two different contexts. First we copied it into anyother array, i.e., list, so it returned all the elements assuming that context is list context. Next we used the same array and tried to store this array in a scalar, so in this case it returned just the number of elements in this array assuming that context is scalar context. Following table lists down the various contexts − Sr.No. Context & 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 Boolean Boolean context is simply any place where an expression is being evaluated to see whether it's true or false. 4 Void This context not only doesn't care what the return value is, it doesn't even want a return value.
  • 14. PERL SCALARS 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. Here is a simple example of using scalar variables −
  • 15. PERL SCALARS NUMERIC SCALAR A scalar is most often either a number or a string. Following example demonstrates the usage of various types of numeric scalars −
  • 16. PERL SCALARS String Scalars Following example demonstrates the usage of various types of string scalars. Notice the difference between single quoted strings and double quoted strings −
  • 17. PERL SCALARS Scalar Operations You will see a detail of various operators available in Perl in a separate chapter, but here we are going to list down few numeric and string operations.
  • 18. PERL SCALARS Multiline Strings If you want to introduce multiline strings into your programs, you can use the standard single quotes as below −
  • 19. PERL ARRAYS 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. Here is a simple example of using the array variables −
  • 20. PERL ARRAYS Here we have used the escape sign () before the $ sign just to print it. Other Perl will understand it as a variable and will print its value. When executed, this will produce the following result − In Perl, List and Array terms are often used as if they're interchangeable. But the list is the data, and the array is the variable.
  • 21. PERL ARRAYS Array Creation Array variables are prefixed with the @ sign and are populated using either parentheses or the qw operator. For example − The second line uses the qw// operator, which returns a list of strings, separating the delimited string by white space. In this example, this leads to a four-element array; the first element is 'this' and last (fourth) is 'array'. This means that you can use different lines as follows −
  • 22. PERL ARRAYS Array Creation You can also populate an array by assigning each value individually as follows − Accessing Array Elements When accessing individual elements from an array, you must prefix the variable with a dollar sign ($) and then append the element index within the square brackets after the name of the variable. For example −
  • 23. PERL ARRAYS Array Creation Array indices start from zero, so to access the first element you need to give 0 as indices. You can also give a negative index, in which case you select the element from the end, rather than the beginning, of the array. This means the following −
  • 24. PERL IF ELSE (CONDITIONAL STATEMENTS) Perl conditional statements helps in the decision making, which require that the programmer specifies one or more conditions to be evaluated or tested by the program, along with a statement or statements to be executed if the condition is determined to be true, and optionally, other statements to be executed if the condition is determined to be false. Following is the general from of a typical decision making structure found in most of the programming languages −
  • 25. PERL IF ELSE (CONDITIONAL STATEMENTS) The ? : Operator Let's check the conditional operator ? :which can be used to replace if...else statements. It has the following general form − Exp1 ? Exp2 : Exp3; Where Exp1, Exp2, and Exp3 are expressions. Notice the use and placement of the colon. The value of a ? expression is determined like this: Exp1 is evaluated. If it is true, then Exp2 is evaluated and becomes the value of the entire ? expression. If Exp1 is false, then Exp3 is evaluated and its value becomes the value of the expression. Below is a simple example making use of this operator −
  • 26. PERL IF ELSE (CONDITIONAL STATEMENTS)
  • 27. PERL LOOPS 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. A loop statement allows us to execute a statement or group of statements multiple times and following is the general form of a loop statement in most of the programming languages Perl programming language provides the following types of loop to handle the looping requirements.
  • 28. PERL LOOPS Loop Control Statements Loop control statements change the execution from its normal sequence. When execution leaves a scope, all automatic objects that were created in that scope are destroyed. Perl supports the following control statements 1. next statement Causes the loop to skip the remainder of its body and immediately retest its condition prior to reiterating. 2. last statement Terminates the loop statement and transfers execution to the statement immediately following the loop. 3. continue statement A continue BLOCK, it is always executed just before the conditional is about to be evaluated again. 4. redo statement The redo command restarts the loop block without evaluating the conditional again. The continue block, if any, is not executed. 5. goto statement Perl supports a goto command with three forms:
  • 29. PERL IF ELSE (CONDITIONAL STATEMENTS) • The Infinite Loop • A loop becomes infinite loop if a condition never becomes false. The for loop is traditionally used for this purpose. Since none of the three expressions that form the for loop are required, you can make an endless loop by leaving the conditional expression empty.
  • 30. PERL OPERATORS • What is an Operator? • 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, but following is a list of important and most frequently used operators − • Arithmetic Operators • Equality Operators • Logical Operators • Assignment Operators • Bitwise Operators • Logical Operators • Quote-like Operators • Miscellaneous Operators
  • 31. PERL OPERATORS • Perl Arithmetic Operators Assume variable $a holds 10 and variable $b holds 20, then following are the Perl arithmatic operators − Sr.No. Operator & Description 1 + ( Addition ) Adds values on either side of the operator Example $a + $b will give 30 − 2 - (Subtraction) Subtracts right hand operand from left hand operand Example $a - $b will give -10 − 3 * (Multiplication) Multiplies values on either side of the operatorExample $a * $b will give 200 − 4 / (Division) Divides left hand operand by right hand operand Example $b / $a will give 2 − 5 % (Modulus) Divides left hand operand by right hand operand and returns remainder Example − $b % $a will give 0 6 ** (Exponent) Performs exponential (power) calculation on operators Example $a**$b will give −
  • 32. PERL OPERATORS • Perl Equality Operators • These are also called relational operators. Assume variable $a holds 10 and variable $b holds 20 then, lets check the following numeric equality operators − Sr.No. Operator & Description 1 == (equal to) Checks if the value of two operands are equal or not, if yes then condition becomes true. Example ($a == $b) is not true. − 2 != (not equal to) Checks if the value of two operands are equal or not, if values are not equal then condition becomes true. Example ($a != $b) is true. − 3 <=> Checks if the value of two operands are equal or not, and returns -1, 0, or 1 depending on whether the left argument is numerically less than, equal to, or greater than the right argument. Example ($a <=> $b) returns -1. − 4 > (greater than) Checks if the value of left operand is greater than the value of right operand, if yes then condition becomes true. Example ($a > $b) is not true. − 5 < (less than) Checks if the value of left operand is less than the value of right operand, if yes then condition becomes true. Example ($a < $b) is true. − 6 >= (greater than or equal to) Checks if the value of left operand is greater than or equal to the value of right operand, if yes then condition becomes true. Example ($a >= $b) is not true. − 7 <= (less than or equal to)
  • 33. PERL OPERATORS • Perl Assignment Operators • Assume variable $a holds 10 and variable $b holds 20, then below are the assignment operators available in Perl and their usage − Sr.No. Operator & Description 1 = Simple assignment operator, Assigns values from right side operands to left side operand Example $c = $a + $b will assigned value of $a + $b into $c − 2 += Add AND assignment operator, It adds right operand to the left operand and assign the result to left operand Example $c += $a is equivalent to $c = $c + $a − 3 -= Subtract AND assignment operator, It subtracts right operand from the left operand and assign the result to left operand Example $c -= $a is equivalent to $c = $c - $a − 4 *= Multiply AND assignment operator, It multiplies right operand with the left operand and assign the result to left operand Example $c *= $a is equivalent to $c = $c * $a − 5 /= Divide AND assignment operator, It divides left operand with the right operand and assign the result to left operand Example $c /= $a is equivalent to $c = $c / $a − 6 %= Modulus AND assignment operator, It takes modulus using two operands and assign the result to left operand Example $c %= $a is equivalent to $c = $c % a − 7 **=
  • 34. PERL OPERATORS • Perl Logical Operators • There are following logical operators supported by Perl language. Assume variable $a holds true and variable $b holds false then − Sr.No. Operator & Description 1 and Called Logical AND operator. If both the operands are true then then condition becomes true. Example ($a and $b) is false. − 2 && C-style Logical AND operator copies a bit to the result if it exists in both operands. Example ($a && $b) is false. − 3 or Called Logical OR Operator. If any of the two operands are non zero then then condition becomes true. Example ($a or $b) is true. − 4 || C-style Logical OR operator copies a bit if it exists in eather operand. Example ($a || $b) is true. − 5 not
  • 35. PERL OPERATORS • Miscellaneous Operators • There are following miscellaneous operators supported by Perl language. Assume variable a holds 10 and variable b holds 20 then − Sr.No. Operator & Description 1 . Binary operator dot (.) concatenates two strings. Example If $a = "abc", $b = "def" then $a.$b will give "abcdef" − 2 x The repetition operator x returns a string consisting of the left operand repeated the number of times specified by the right operand. Example ('-' x 3) will give ---. − 3 .. The range operator .. returns a list of values counting (up by ones) from the left value to the right value Example (2..5) will give (2, 3, 4, 5) − 4 ++ Auto Increment operator increases integer value by one Example $a++ will give 11 − 5 -- Auto Decrement operator decreases integer value by one Example $a-- will give 9 − 6 -> The arrow operator is mostly used in dereferencing a method or variable from an object or a class name