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