SL Unit-Ii Perl
SL Unit-Ii Perl
When you run a Perl program, it's first compiled into a byte
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.
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.
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
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
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;
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
++
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:
$name = "Ali";
$age = 10;
senior citizen";
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.
1. if Statement
3. if...elsif statement
4. unless Statement
5. unless...else statement
6. unless...elsif statement
7. switch Statement
if Statement
statement }
else
if(boolean_expression){ {
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:
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:
# 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.
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 −
together.
@numbers = (1,3,(4,5,6));
print "numbers = @numbers\n";
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";
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 −
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{'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 = ('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:
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“;