0% found this document useful (0 votes)
29 views84 pages

SL Unit-Ii Perl

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
29 views84 pages

SL Unit-Ii Perl

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 84

UNIT – II Syllabus

Introduction to PERL and Scripting, Scripts and


Programs, Origin of Scripting, Scripting Today,
Characteristics of Scripting Languages, Uses for
Scripting Languages, Web Scripting, and the universe
of Scripting Languages. PERL- Names and Values,
Variables, Scalar Expressions, Control Structures,
arrays, list, hashes, strings, pattern and regular
expressions, subroutines.
Perl

Perl is a general-purpose programming

language originally developed for script

manipulation and now used for a wide range of

tasks including system administration, web

development, network programming, GUI

development, and more.


Larry Wall.
What is Perl?

 Perl is a high-level, general-purpose, interpreted, dynamic


programming language.
 Perl is a term stands for “Practical Extraction and Reporting
Language” even though there is no acronym for Perl.
 It was introduced by Larry Wall in 1987. Perl language was
specially designed for text editing.
 But now, it is widely used for a variety of purposes including
Linux system administration, network programming, web
development, etc.
Where is Perl used?
Perl is interpreted

Perl is an interpreted language, which means that your code

can be run as it is, without a compilation stage that creates a non

portable executable program.

When you run a Perl program, it's first compiled into a byte

code, which is then converted ( as the program runs) into

machine instructions. So it is not quite the same as shells, or

Tcl, which are strictly interpreted without an intermediate

representation.
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 −


1. scalars
2. arrays of scalars
3. hashes of scalars

Note: - hashes of scalars also known as associative arrays.


Cont ..
Scalars:
Scalars are simple variables. They are preceded by a dollar sign
($). A scalar is a number, a string, or a reference.
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 (@).
Hashes:
Hashes are unordered sets of key/value pairs that you access
using the keys as subscripts. They are preceded by a percent sign
(%).
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
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).
Variables

 Variables are the reserved memory locations to store values. This means that
when we create a variable, we 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.
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.

 $age = 25; # An integer assignment


 $name = "John Paul"; # A string
 $salary = 1445.50; # A floating point
Scalar Variables
A scalar variable will proceed by a dollar sign ($) and it can store
a number, a string, or a reference.

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.

$age = 25; # An integer assignment


$name = "John Paul"; # A string
$salary = 1445.50; # A floating point
print "Age = $age\n";
print "Name = $name\n";
print "Salary = $salary\n“;
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.
@ages = (25, 30, 40);
@names = ("John Paul", "Lisa", "Kumar");
print "\$ages[0] = $ages[0]\n";
print "\$ages[1] = $ages[1]\n";
print "\$ages[2] = $ages[2]\n";
print "\$names[0] = $names[0]\n";
print "\$names[1] = $names[1]\n";
print "\$names[2] = $names[2]\n“;
Operators
Perl language supports many operator types, but following is
a list of important and most frequently used operators –

1. Arithmetic Operators
2. Relational Operators
3. Logical Operators
4. Assignment Operators
5. Bitwise Operators
6. Conditional Operators
7. Increment/Decrement Operators
Arithmetic Operators
Assume variable $a holds 10 and variable $b holds 20 then
Operator Description Example
Addition - Adds values on either side of the operator $a + $b will give 30
+
Subtraction - Subtracts right hand operand from left hand operand $a - $b will give -10
-
Multiplication - Multiplies values on either side of the operator $a * $b will give 200
*
Division - Divides left hand operand by right hand operand $b / $a will give 2
/
Modulus - Divides left hand operand by right hand operand and $b % $a will give 0
% returns remainder

Exponent - Performs exponential (power) calculation on operators $a**$b will give 10 to


** the power 20
Relational Operators
Assume variable $a holds 10 and variable $b holds 20 then

Operator Description Example


Checks if the values of two operands are equal or not, if yes then condition becomes true.
== ($a == $b) is not true.

Checks if the values of two operands are equal or not, if values are not equal then
!= ($a != $b) is true.
condition becomes true.

Checks if the value of two operands are equal or not, and returns -1, 0, or 1 depending on
($a <=> $b) returns
whether the left argument is numerically less than, equal to, or greater than the right
<=> argument.
-1.
Checks if the value of left operand is greater than the value of right operand, if yes then
> ($a > $b) is not true.
condition becomes true.

Checks if the value of left operand is less than the value of right operand, if yes then
< ($a < $b) is true.
condition becomes true.

Checks if the value of left operand is greater than or equal to the value of right operand, if
($a >= $b) is not true.
>= yes then condition becomes true.

Checks if the value of left operand is less than or equal to the value of right operand, if yes
<= ($a <= $b) is true.
then condition becomes true.

 Returns -1 if $a is less than $b.
 Returns 0 if $a is equal to $b.
 Returns 1 if $a is greater than $b.
my $a = 5;
my $b = 10;

my $result = $a <=> $b; # Spaceship operator comparison

if ($result == -1) {
print "$a is less than $b\n";
} elsif ($result == 0) {
print "$a is equal to $b\n";
} elsif ($result == 1) {
print "$a is greater than $b\n";
}
String Relational Operators
Operator Description Example

lt Returns true if the left argument is string wise less than the right argument. ($a lt $b) is true.

gt Returns true if the left argument is string wise greater than the right argument. ($a gt $b) is false.

le Returns true if the left argument is string wise less than or equal to the right ($a le $b) is true.
argument.

ge Returns true if the left argument is string wise greater than or equal to the right ($a ge $b) is false.
argument.

eq Returns true if the left argument is string wise equal to the right argument. ($a eq $b) is false.

ne Returns true if the left argument is string wise not equal to the right argument. ($a ne $b) is true.
Returns -1, 0, or 1 depending on whether the left argument is stringwise less ($a cmp $b) is -1.
cmp than, equal to, or greater than the right argument.
Assignment Operators
Assume variable $a holds 10 and variable $b holds 20 then
Operator Description Example
$c = $a + $b will assigned value of $a + $b into
=
Simple assignment operator, Assigns values from right side operands to left side operand
$c

Add AND assignment operator, It adds right operand to the left operand and assign the result $c += $a is equivalent to $c = $c + $a
+= to left operand

Subtract AND assignment operator, It subtracts right operand from the left operand and $c -= $a is equivalent to $c = $c - $a
-= assign the result to left operand

Multiply AND assignment operator, It multiplies right operand with the left operand and $c *= $a is equivalent to $c = $c * $a
*= assign the result to left operand

Divide AND assignment operator, It divides left operand with the right operand and assign $c /= $a is equivalent to $c = $c / $a
/= the result to left operand

Modulus AND assignment operator, It takes modulus using two operands and assign the $c %= $a is equivalent to $c = $c % a
%= result to left operand

Exponent AND assignment operator, Performs exponential (power) calculation on operators $c **= $a is equivalent to $c = $c ** $a
**= and assign value to the left operand
Bitwise Operators
Bitwise operator works on bits and performs bit by bit operation.
Assume if $a = 60; and $b = 13; Now in binary format they will be as follows −

$a = 0011 1100
$b = 0000 1101
--------------------
$a&$b = 0000 1100
$a|$b = 0011 1101
$a^$b = 0011 0001
~$a = 1100 0011
Cont ..
Operator Description Example
Binary AND Operator copies a bit to the result if it exists in both ($a & $b) will give 12 which is 0000 1100
& operands.

Binary OR Operator copies a bit if it exists in eather operand. ($a | $b) will give 61 which is 0011 1101
|
Binary XOR Operator copies the bit if it is set in one operand but not ($a ^ $b) will give 49 which is 0011 0001
^ both.

Binary Ones Complement Operator is unary and has the efect of (~$a ) will give -61 which is 1100 0011 in 2's
~ 'flipping' bits. complement form due to a signed binary
number.

Binary Left Shift Operator. The left operands value is moved left by the $a << 2 will give 240 which is 1111 0000
<< number of bits specified by the right operand.

Binary Right Shift Operator. The left operands value is moved right by $a >> 2 will give 15 which is 0000 1111
>> the number of bits specified by the right operand.
Logical Operators
Assume variable $a holds true and variable $b holds false then

Operator Description Example


Called Logical AND operator. If both the operands are true then
and then condition becomes true. ($a and $b) is false.
C-style Logical AND operator copies a bit to the result if it exists in
&& both operands. ($a && $b) is false.
Called Logical OR Operator. If any of the two operands are non
or zero then then condition becomes true. ($a or $b) is true.
C-style Logical OR operator copies a bit if it exists in eather
|| operand. ($a || $b) is true.
Called Logical NOT Operator. Use to reverses the logical state of
not its operand. If a condition is true then Logical NOT operator will not($a and $b) is true.
make false.
Increment / Decrement Operators
Assume variable a holds 10 and variable b holds 20 then

Operator Description Example

++
Auto Increment operator increases integer value by
one $a++ will give 11

--
Auto Decrement operator decreases integer value
by one $a-- will give 9
Conditional Operator (?:)
Which can be used to replace if...else statement. It has the
following general form:

Exp1 ? Exp2 : Exp3; Where Exp1, Exp2, and Exp3 are


expressions.

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

$name = "Ali";

$age = 10;

$status = ($age > 60 )? "A senior citizen" : "Not a

senior citizen";

print "$name is - $status\n";


Input and Output Operations
In Perl there are three streams:

1. Input stream
2. Output stream
3. Error stream.

The input stream is associated with keyboard input and it is denoted by STDIN.
The output stream is associated with screen output and it is denoted by STDOUT.
The error stream is associated with programs output for error messages and it is denoted by STDERR.

Keyboard Input: The Perl provide the keyboard input by line input operator which is denoted by angular
brackets.
Example: $num = <STDIN>;

Thus whatever we type of the keyboard gets stored in the variable num. This includes the newline character as
well. Hence we can remove the new line characters by making use of chomp.

Example chomp( $num = <STDIN> )


Screen Output: For screen output we use print statement.
Example: print “Programming in Perl”;
Conditional or Selection Statements

Perl programming language provides the following types of conditional stateme

1. if Statement

2. if… else statement

3. if...elsif statement

4. unless Statement

5. unless...else statement

6. unless...elsif statement

7. switch Statement
if Statement

A Perl if statement consists of a boolean expression followed by


one or more statements.
Syntax of an if statement
if(boolean_expression){
# statement(s) will execute if the given
condition is true
} Example:
$a = 10;
if( $a < 20 ) {
printf "a is less than 20\
n";
}
if … else Statement

If the Boolean expression Example:


evaluates to true, then the if
block of code will be executed $a = 100;
otherwise else block of code if( $a < 20 ) {
will be executed.
printf "a is less than 20\

Syntax of an if … else n";

statement }
else
if(boolean_expression){ {

# statement(s) printf "a is greater than


} 20\n"; }
else{
# statement(s)
}
if...elsif statement
Syntax of
an if...elsif...else Example:
$a = 100;
if(boolean_expression 1){ if( $a == 20 ){
# statement(s) printf "a has a value which
} is 20\n";
elsif( boolean_expression 2){ }elsif( $a == 30 ){
# statement(s)} printf "a has a value which
elsif( boolean_expression 3){ is 30\n";
# statement(s) }else{
} printf "a has a value which
else{ is $a\n";
# statement(s) }
}
unless Statement
If the boolean expression evaluates to false, then the block of code inside the unless
statement will be executed. If boolean expression evaluates to true then the first set
of code after the end of the unless statement (after the closing curly brace) will be
executed.

Syntax of an unless Example:


statement
$a = 20;
unless(boolean_expres unless( $a < 20 )
{
sion)
printf "a is not less than
{ 20\n";
# statement(s) }
will execute if
the given condition is
false
}
Unless … else Statement
The syntax of Example:
an unless...else
$a = 100;
unless( $a == 20 ){
unless(boolean_expres printf "given condition is
sion){ # false\n";
}
statement(s) else
} {
else{ printf "given condition is
true\n";
# statement(s) }
}
Unless … elseif Statement
Syntax of
an unless...elsif...else Example:

unless(boolean_expression 1) $a = 20;
unless( $a == 30 ){
{
printf "a has a value which is
# statement(s) not 20\n";
} }
elsif( boolean_expression 2) elsif( $a == 30 ){
{ printf "a has a value which is
# statement(s) 30\n";
} }else{
elsif( boolean_expression 3) printf "a has a value which is
{ $a\n";
}
# statement(s)}
else{
# statement(s)
Switch Statement
A switch statement allows a variable to be tested for equality against a list
of values. Each value is called a case, and the variable being switched on
is checked for each switch case.
switch statement Syntax:
use Switch;
$var = 10;
@arr = (10, 20, 30);
switch($var) {
case 10 { print("$var matches this case\n");
}
case "x" { print("string type")
}
case [1..10,42] { print("$var present in list\n");
}
case (\@arr) {
print("$var present in array @arr");
}
else { print("None of the cases match");
}
}
Cont ..
If a case block executes an
untargeted next, control is switch statement
immediately transferred to the
statement after the case
Example:
use Switch;
statement (i.e., usually another
$var = 10;
case), rather than out of the
@array = (10, 20, 30);
surrounding switch block.
%hash = ('key1' => 10, 'key2' => 20);
Not every case needs to switch($var){
case 10 { print "number 100\
contain a next. If
n";next; }
no next appears, the flow of
case "a" { print "string a"; }
control will not fall
case [1..10,42] { print "number in list";
through subsequent cases.
next;}
case (\@array) { print "number in list";
next;}
else { print "previous case not
true"; }
}
Iterative Statements
The following loop control statements are available in perl:

 while Statement
 do...while Statement
 until Statement
 for Statement
 foreach Statement
While loop statement
A while loop statement repeatedly executes a single statement or a
block of statements as long as a given condition is true.

syntax of a while :

while(condition)
{
statement(s);
}
Note: Here the condition may be any expression.

Example: $a = 10;
while( $a < 20 ){
printf "Value of a:
$a\n";
$a = $a + 1;
}
do...while Statement
A do...while loop is similar to a while loop, except that a do...while
loop is guaranteed to execute at least one time.

Syntax:

do{
statement(s);
}while( condition );

Example: $a = 10;
do{
printf "Value of a: $a\n";
$a = $a + 1;
}while( $a < 20 );
until Statement
A until loop statement repeatedly executes a single statement or
a block of statements as long as a given condition is false.

Syntax:

until(condition)
{
statement(s);
}

Example: $a = 5;
until( $a > 10 ){
printf "Value of a: $a\n";
$a = $a + 1;
}
For Statement
A for loop is a repetition control structure that allows us to
execute a single statement or group of statements for
specific number of times.

Syntax:

for ( initialization; condition; increment /decrement)


{
statement(s);
}

Example:
for( $a = 10; $a < 20;
$a = $a + 1 ){
print "value of a: $a\n";
}
foreach Statement
The foreach loop iterates over a list value and sets the
control variable (var) to be each element of the list.

Syntax:

foreach var (list)


{
#statement(s)
}
Example:
@list = (2, 20, 30, 40, 50);
foreach $a(@list){
print "value of a: $a\
n";
}
Nested Loops
A loop can be nested inside of another loop. Perl allows to nest
all type of loops to be nested.

The syntax for a nested for loop statement in Perl is as follows:

for ( init; condition; increment ){


for ( init; condition; increment ){
statement(s);
}
statement(s);
}
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.

Control Statement Description

next statement is used within loops to skip the


next statement rest of the current iteration and move on to
the next one..

last statement is used to exit a loop


last statement
prematurely

A continue BLOCK, it is always executed just before the


continue statement conditional is about to be evaluated again.

The Perl redo statement restarts the current


loop without evaluation of the control
redo statement statement. Further statements in the block
next statement
# Perl program with the 'next' statement
# Loop from 1 to 5
for my $i (1..5) {

# Skip the iteration if $i is equal to 3


if ($i == 3) {
next;
}

# Print the current value of $i


print "Current value of \$i: $i\n";
}

# Output:
# Current value of $i: 1
# Current value of $i: 2
# Current value of $i: 4
# Current value of $i: 5
last statement
$a = 10;
while( $a < 20 ) {
if( $a == 15) {
# terminate the loop.
$a = $a + 1;
last;
}
print "value of a: $a\n";
$a = $a + 1;
}
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
Continue statements
#!/usr/bin/perl
$a = 0;
while($a < 3) {
print "Value of a = $a\n";
} continue {
$a = $a + 1;
}
Redo statement
$a = 0;
while($a < 7)
{
if( $a == 5 )
{
$a = $a + 1;
redo;
}
print "Value of a = $a\n";
} continue
{
$a = $a + 1;
}
Value of a = 0
Value of a = 1
Value of a = 2
Value of a = 3
Value of a = 4
Value of a = 6
Array Creation
Array variables are prefixed with the @ sign and are populated using either parentheses or the qw
operator.
@array= (1, 2, 'Hello');
@array = qw/This is an array/;
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'.
@days = qw/Monday
Tuesday
...
Sunday/;
You can also populate an array by assigning each value individually as follows
$array[0] = 'Monday';
...
$array[6] = 'Sunday‘;
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.

 @days = qw/Mon Tue Wed Thu Fri Sat Sun/;

 print "$days[0]\n";

 print "$days[1]\n";

 print "$days[2]\n";

 print "$days[6]\n";

 print "$days[-1]\n";

 print "$days[-7]\n“;
Sequential Number Arrays

Perl offers a shortcut for sequential numbers and letters. Rather than
typing out each element when counting to 100 for example.

@var_10 = (1..10);
@var_20 = (10..20);
@var_abc = (a..z);
print "@var_10\n"; # Prints number from 1 to
10
print "@var_20\n"; # Prints number from 10
to 20
print "@var_abc\n"; # Prints number from a to
z
Array Size, Adding and Removing Elements
The size of an array can be determined using the scalar context on the array - the returned value
will be the number of elements in the array −

@array = (1,2,3); # add one element at the beginning of the


print "Size: ",scalar @array,"\n"; array
# create a simple array unshift(@coins, "Dollar");
@coins = print "3. \@coins = @coins\n";
("Quarter","Dime","Nickel"); # remove one element from the last of the
print "1. \@coins = @coins\n"; array.
# add one element at the end of pop(@coins);
the array print "4. \@coins = @coins\n";
push(@coins, "Penny"); # remove one element from the beginning
print "2. \@coins = @coins\n"; of the array.
shift(@coins);
Slicing & Sorting Array Elements
We can also extract a "slice" from an array , we can select more than one item from an array in
order to produce another array.
@days = qw/Mon Tue Wed Thu Fri Sat Sun/;
@weekdays = @days[3,4,5];
print "@weekdays\n";
The sort() function sorts each element of an array according to the ASCII Numeric standards.
# define an array
@foods = qw(pizza steak chicken burgers);
print "Before:", @foods;
print "\n";
# sort this array
@foods = sort(@foods);
print "After:" , @foods;
print "\n";
Merging Arrays
 Because an array is just a comma-separated sequence of values. We can combine them

together.
 @numbers = (1,3,(4,5,6));
 print "numbers = @numbers\n";

 This will produce the following result −


 numbers = 1 3 4 5 6

 The embedded arrays just become a part of the main array as shown below:
 @odd = (1,3,5);
 @even = (2, 4, 6);
 @numbers = (@odd, @even);
 print "numbers = @numbers\n";

 This will produce the following result −


 numbers = 1 3 5 2 4 6
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 −

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


print "\$data{'John Paul'} = $data{'John Paul'}\n";
print "\$data{'Lisa'} = $data{'Lisa'}\n";
print "\$data{'Kumar'} = $data{'Kumar'}\n";

This will produce the following result


$data{'John Paul'} = 45
$data{'Lisa'} = 30
$data{'Kumar'} = 40
Creating Hashes
Hashes are created in one of the two following ways. In the first method, we 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. For example −

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

For clarity, you can use => as an alias for , to indicate the key/value pairs as follows −

%data = ('John Paul' => 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. For example −

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

print "$data{'John Paul'}\n";

print "$data{'Lisa'}\n";

print "$data{'Kumar'}\n";
Extracting Slices

You can 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 :

%data = (‘JohnPaul’ => 45, ‘Lisa’ => 30,’Kumar’ => 40);

@sss= @data{‘JohnPaul’, ‘Lisa’};


print "Array : @sss\n“;
Extracting Keys and Values
Similarly, we can use values function to get a list of
We can get a list of all of the keys all the values. This function has the following
syntax:
from a hash by using keys function, values %HASH
which has the following syntax:
This function returns a normal array consisting of all
keys %HASH the values of the named hash. Following is the
%data = ('John Paul' => 45, 'Lisa' example:
=> 30, 'Kumar' => 40); %data = ('John Paul' => 45, 'Lisa' => 30, 'Kumar'
@names = keys %data; => 40);
print $names[0], "\n"; @ages = values %data;
print $names[1], "\n"; print "$ages[0]\n";
print $names[2], "\n"; print "$ages[1]\n";
print "$ages[2]\n";
Getting Hash Size
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 as follows:

%data = ('John Paul' => 45, 'Lisa' => 30, 'Kumar' => 40);
@keys = keys %data;
$size = @keys;
print "1 - Hash size: is $size\n";
@values = values %data;
$size = @values;
print "2 - Hash size: is $size\n“;
Add and Remove Elements in Hashes
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 as shown below in the example:

%data = ('John Paul' => 45, 'Lisa' => 30, 'Kumar' => 40);
# delete the same element from the hash;
@keys = keys %data;
$size = @keys; delete $data{'Ali'};
print "1 - Hash size: is $size\n"; @keys = keys %data;
# adding an element to the hash; $size = @keys;
$data{'Ali'} = 55; print "3 - Hash size: is $size\n";
@keys = keys %data;
$size = @keys;
print "2 - Hash size: is $size\n";
Pattern Matching
A regular expression is a string of characters that defines a specific pattern.
The Perl regular expression syntax is quite similar with that of awk, grep
and sed.
There are three regular expression operators inside Perl:

The regular expression is always given within / /.


Basics of Pattern Matching: For testing the matching for =~ is used.
If we use !~ then it will return true for non-match.
In Perl regular expression are classified into 3 categories. These are:
1.Match Regular Expression
2.Substitute (Search and replace) Regular Expression
3.Transliteration Regular Expression
Matching Regular Expressions
The match operator, / /, is used to match a string or statement
to a regular expression.
Example 1:
$line = "This is Scripting Language.";
if ($line =~ /Scri/){
print "Matching\n";
}else{
print "Not Matching\n";
}
if ($line !~ /scri/){
print "Matching\n";
}else{
print "Not Matching\n";
}
Cont..
The match operator “m//” is used to match a
string or a statement against a regular
expression.
 The forward slash used in the operator
( m// ) acts as the delimiter and this delimiter
can also be like m{}, m(), and m><, etc.
The expression is written in between two
forward slashes used in the operator.
Example 1: Simple Match
my $string = "Hello, Perl!";
if ($string =~ m/Perl/) {
print "Match found!\n";
} else {
print "No match found.\n";
}
Substitute Regular Expression
The substitution operator is just an extension
of the matched operator. It allows the
replacement of text matched with some new
text.
Its basic syntax is:
s/oldPattern/newPattern /;
my $text = "Hello, World!";
$text =~ s/World/Universe/;
print $text; # Output: Hello, Universe!
Translation operator is similar as substitution
Translation Regular Expression

operator. But translation does not use regular


expression for search on replacement values.
Its basic syntax is:
tr/oldLetter/newLetter /;
$string = "hello world";
$string =~ tr/aeiou/AEIOU/;
print "Transformed string: $string\n";
Cont..
>$ string=“10001”;
>$string=~s/0/9/;
19001
>$string=~tr/0/9/;
19991
Meta-characters
. (dot): Matches any single character except a
newline character.
"cat" =~ /c.t/; # Matches "cat“
"a" =~ /./; # Matches any single character
"ab" =~ /../; # Matches any two characters
"abc" =~ /.../; # Matches any three characters
*(asterisk): Matches the preceding character,
character class, or sub pattern zero or more
times.
" abbbbcd " =~ / ab*c /; # Match found:
abbbbc
Cont..
+ (plus): Matches the preceding character,
character class, or sub pattern one or more
times.
"foooobar" =~ /o+/; # Matches "oooo"
$ (dollar): Matches the end of a string.
"hello" =~ /lo$/; # Matches "lo“
"end" =~ /end$/; # Matches because "end"
ends with "end"
"start" =~ /end$/; # Does not match
Cont..
^ (caret): Matches the beginning of a string.
"hello" =~ /^he/; # Matches "he“
"start" =~ /^start/; # Matches because
"start" starts with "start"
"end" =~ /^start/; # Does not match
Cont..
 [] (square brackets): Defines a character class; matches any single
character within the brackets.
"cat" =~ /[aeiou]t/; # Matches "at“
() (parentheses): Groups regular expressions or captures matched
text.
"ababab" =~ /(ab)+/; # Matches "ababab“
| (pipe): Acts as an OR operator, allowing matching of either the
expression before or after the pipe
"cat" =~ /cat|dog/; # Matches "cat“
\ (backslash): Escapes special characters, allowing you to match them
literally.
"3+3=6" =~ /\+/; # Matches "+“
{}(curly braces): used to specify the number of occurrences or a range
of occurrences of the preceding pattern.
my $text = "hellooooo";
if ($text =~ /o{3,}/) {
print "Found three or more 'o's in a row!\n";
}
Meta characters
Character class Meaning
\d Matches with a digit

\D Matches with a non digit

\w Matches with any alphanumeric character

\W Matches with not a word character


This matches any whitespace character. It is
\s equivalent to the character class [ \t\n\r\f]
This matches any non-whitespace character.
\S It is the opposite of \s. It is equivalent to the
character class [^ \t\n\r\f]

\b Word boundary(i.e. start and end of a word)


Examples
 Matching Digits:
my $str = "123abc456";
if ($str =~ /\d+/) {
print "Digits found: $&\n";
}
This will output: Digits found: 123
Matching Words:
my $sentence = "Hello, Perl is awesome!";
if ($sentence =~ /\b(Hello)\b/) {
print "Word found: $1\n";
}
This will output: Word found: Hello
cont,..
 Matching Email Address:
my $email = '[email protected]';
if ($email =~ /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,3}$/)
{
print "Valid email address\n";
} else {
print "Invalid email address\n";
}
Extracting Captured Groups:
my $text = "Date: 2024-01-31";
if ($text =~ /Date: (\d{4}-\d{2}-\d{2})/) {
print "Found date: $1\n";
}
This will output: Found date: 2024-01-31
Cont..
Case-Insensitive Match:
my $str = "Hello Perl";
if ($str =~ /perl/i) {
print "Case-insensitive match found\n";
}
Matching Multiple Patterns:
my $sentence = "The cat and the hat";
if ($sentence =~ /cat|hat/) {
print "Cat or hat found\n";
}
Cont..
Cont..
Subroutines ( User defined Functions )
A subroutine or function is a group of statements that together performs a task.

Define and Call a Subroutine


The general form of a subroutine definition in Perl programming language is as
follows :
sub subroutine_name{
body of the subroutine
}
Calling Subroutine :
subroutine_name( list of arguments );
Example
# Subroutine definition  We can pass various
sub Hello arguments to a subroutine like
{ any other programming
print "Hello, World!\ language and they can be
n"; accessed inside the function
} using the special array @_.

# Subroutine call  Thus the first argument to


the function is in $_[0], the
Hello(); second is in $_[1], and so on.
Passing Arguments
We can pass arrays and hashes as arguments like any scalar but passing more than one array or
hash normally causes them to lose their separate identities.

Function definition
sub calculate_average {
my @numbers = @_; # Get the array of numbers passed to the
subroutine
my $total = 0;
foreach my $num (@numbers) {
$total += $num; # Add each number to the total
}
my $average = $total / scalar(@numbers); # Calculate the
average
return $average; # Return the average
}
my @example_numbers = (10, 20, 30, 40, 50);
# Calculate the average using the subroutine
Passing Lists to Subroutines
Because the @_ variable is an array, it can be used to supply lists to a subroutine. However, because of the
way in which Perl accepts and parses lists and arrays, it can be difficult to extract the individual elements
from @_. If you have to pass a list along with other scalar arguments, then make list as the last argument as
shown below :
sub PrintHash{
my (%hash) = @_;
foreach my $key ( keys %hash ){
my $value = $hash{$key};
print "$key : $value\n";
}
}
%hash = ('name' => 'Tom', 'age' => 19);
# Function call with hash parameter
PrintHash(%hash);
Returning Value from a Subroutine
You can return a value from subroutine like you do in any other
programming language ( using return statement ). You can return
arrays and hashes from the subroutine.

# Function definition
sub Average{
# get total number of arguments passed.
$n = scalar(@_);
$sum = 0;
foreach $item (@_){
$sum += $item;
}
$average = $sum / $n;
return $average;
}
# Function call
$num = Average(10, 20, 30);
print "Average for the given numbers :
$num\n“;

You might also like