Perl Basics
Content
- Introduction
- Scalar Variable
- Arrays & Hashes
- Conditionals statements and loops
- Operators
- Subroutines
- File handling
- Regular expressions
Introduction
- Perl is a programming language developed by Larry Wall in 1987, especially designed for text processing. It stands for Practical Extraction and Report Language.
- Perl is a general-purpose programming language originally developed for text manipulation and used for a wide range of tasks including web development, system administration, network programming , code generation more.
What is Perl?
- Perl is a stable, cross platform programming language.
- Though Perl is not officially an acronym but few people used it as Practical Extraction and Report Language.
- It is used for mission critical projects in the public and private sectors.
- Perl is an open source software, licensed under its Artistic License, or the GNU General Public License (GPL).
- Perl 1.0 was released to usenet’s alt.comp.sources in 1987.
- The latest version of perl was 5.16.2.
- Perl is listed in the Oxford English Dictionary.
Perl Features
- Perl takes the best features from other languages, such as C, awk, sed, sh, and BASIC, among others.
- Perls database integration interface DBI supports third-party databases including Oracle, Sybase, Postgres, MySQL and others.
- Perl works with HTML, XML, and other mark-up languages.
- Perl supports Unicode.
- Perl supports both procedural and object-oriented programming.
- Perl is extensible. There are over 20,000 third party modules available from the Comprehensive Perl Archive Network (CPAN).
- The Perl interpreter can be embedded into other systems.
Perl is Interpreted
•Perl is an interpreted language, which means that your code can be run as is, without a compilation stage that creates a non portable executable program.
•Traditional compilers convert programs into machine language. 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.
Basic syntax
- All perl statements must end in a semicolon ( ; ).
- Perl case sensitive.
- You can use any text editor to write your perl script.(like vi, vim, gvim more..)
- Save the script file in .pl extension.
- In Perl, comments begin with # (like shell scripts).
- In perl multiline comments like =begin/cut
- The -w option tells Perl to produce extra warning messages at run time.
- #!/usr/local/bin/perl5 –w (or)
- #!/usr/local/bin/perl5
- use warnings;
- To warn at compile time by -c option.
- Inside file : use strict
- Compile as : perl -c filename
Executing a Perl program
- You can run the script directly if you make the script executable, and the first line is of the following form ( #!/usr/… must start from the first column):
- Here /usr/bin/perl is actual the perl interpreter binary.
- Vi simple.pl #Create a PERL FILE
$ chmod 755 #permissions
$ cat simple.pl
#!/usr/local/bin/perl -w #put this shebang in your script in first line
$ ./simple.pl (or)
$ perl simple.pl #Run a perl program from the unix command line
Here is a “hello world” Perl program:
#!/usr/local/bin/perl5 -w
print “Hello world\n”;
The print command sends the string to the screen, and “\n” adds a newline.
Output :
Hello world
Perl Data types
- Scalar
- Arrays
- hashes
Scalar variables
- Scalar values can be string, integers, floating point numbers or references.
- Scalar variables begin with $ followed by a letter, and then possibly more letters, digits, or underscores. (e.g., $n, $n1, $name, $first_name).
- Scalar variables are case sensitive.
Assigning Scalar Variables
Scalars are assigned using “=“
$scalar = expression;
$animal = “dog”; #string
$number = 34 #number
$scalar_ref = \$scalar; #reference
Print “$animal\n”
Print “$number\n”;
Print”$scalar_ref\n”
Output:
- dog
- 34
- SCALAR(0x227e320)
Single quoted
- Single quoted strings: Prints string as it is !
- Except ‘ and \
Examples: – $str = ‘I don\’t think so.’ ;
print “$str\n”;
Output : I don’t think so.
Double quoted
“\\” – an actual, single backslash character
“\$” – a single $ character
”\@” – a single @ character
“\n” – newline
“\e” – escape
“\t” – tab
“\b” – backspace
“\101” – character represented by octal value, 101 => A
“\x41” – character represented by hexa-decimal value, 41 => A
A feature of double-quoted strings is that they are variable interpolated, meaning that scalar and array variables within the strings are replaced with their current values when the strings are used.
String Operators
String values can be concatenated with the “.” operator.
$look = “Somthing!\n”;
$out = “Nature will be making “.”$look\n”;
print “$out\n”;
output : Nature will be make Somthing!
String repetition operator : x
$b = “vdd” x 3;
print “$b\n”;
output: vddvddvdd
Numerical Scalar Variables (Contd …)
Internally, all numerical scalar values are stored as floats (so you don’t have to worry about integer division in Perl like you do in C++).
Perl supports the usual C++ numerical operations:
$a = 25;
print “$a\n”; # $a is now 25
$a += 5;
print “$a\n”; # $a is now 30
$a *= 3;
print “$a\n”; # $a is now 90
$a++;
print “$a\n”; # $a is now 91
–$a;
print “$a\n”; # $a is now 90
$result = ($a + 2) * 3.4;
print “$ result \n”; # $result is 312.8
Scalar variables
Use strict: forces you to declare your variables before using them. Also controls references & subroutines.
<STDIN>grabs one line of input, including the newline character. So, after:
$name =<STDIN> ;
To delete the newline, the chomp() function takes a scalar variable, and removes the trailing newline if present. (If there is no newline at the end, it does nothing)
chomp($name);
A shortcut to do both operations in one line is:
chomp($name = );
Input from STDIN
$cat file
print “What is your name? “;
$name =<STDIN>;
chomp ($name);
print “Hello $name !\n”;
Output:
$ ./file
What is your name? Kommu
Hello Kommu !
Chop function
Chop : A built-in function is chop. Takes a single argument and removes the last character.
$x = “hello world”;
$y=chop($x); # $x is now “hello worl” , $y is d
$k=chomp($x); # $x is “hello worl” , $k is 0
$x=“hello world\n”;
$y=chop($x); # $x is now “hello world”, $y is “\n” $x = “hello world\n”;
$k=chomp($x); # $x is “hello world”, $k is 1
Scalar variables
Comparison Numeric String
——————————————————————————————-
equal = eq
not equal != ne
less than < lt
more than > gt
less than equal to <= le
greater than equal to >= ge
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.
Examples for Array
#!/usr/bin/perl
@net_name = (“vdd”, “VSS”, “signal”, 66);
Print “\$net_name[0] = $net_name[0]\n”; #print the first value of array
Print “\$net_name[1] = $net_name[1]\n”;
Print “$net_name[0]\n”;
Print “@net_name\n”;
Output :
$net_name[0] = Vdd
$net_name[1] = Vss
Vdd
Vdd vss signal 66
Sequential Number Arrays
@var_10 = (1..10);
print “@var_10\n”; # Prints number from 1 to 10
@var_20 = (10..20);
print “@var_20\n”; # Prints number from 10 to 20
@var_abc = (a..z);
print “@var_abc\n”; # Prints number from a to z
Output: Here double dot (..) is called range operator. This will produce the following result
1 2 3 4 5 6 7 8 9 10
10 11 12 13 14 15 16 17 18 19 20
a b c d e f g h i j k l m n o p q r s t u v w x y z
Adding Elements in Array
push @ARRAY, LIST:
-Pushes the values of the list onto the end of the array.
#!/usr/bin/perl
@net_name = (“vdd”, “vss”, “signal”); #create array
print “1. @net_name\n”;
push(@net_name, “Dvdd”); #add on element at end of the array
print”2.list of array: @net_name\n”;
Output
1. vdd vss signal
2.list of array: vdd vss signal Dvdd
Adding Elements in Array
unshift @ARRAY, LIST:
-Prepends list to the front of the array, and returns the number of elements in the new array.
#!/usr/bin/perl
@net_name = (“vdd”, “vss”, “signal”); #create array
print “1. @net_name\n”;
unshift(@net_name, “Dvss”); #add on element at starting of the array
print”2.list of array: @net_name\n”;
Output
1. vdd vss signal
2.list of array: Dvss vdd vss signal
Removing Elements in Array
pop @ARRAY
::Remove one element from the last of the array.
#!/usr/bin/perl
@net_name = (“vdd”, “vss”, “signal”); #create array
print “1. @net_name\n”;
pop(@net_name); # Remove one element from the last of the array
print”2.list of array: @net_name\n”;
Output
1. vdd vss signal
2.list of array: vdd vss
pop @ARRAY
::Remove one element from the beginning of the array.
#!/usr/bin/perl
@net_name = (“vdd”, “vss”, “signal”); #create array
print “1. @net_name\n”;
shift(@net_name); # Remove one element from the beginning of the array
print”2.list of array: @net_name\n”;
Output
1. vdd vss signal
2.list of array: vss signal
Slicing Array Elements
Can also extract a “slice” from an array – that is, you can select more than one item from an array in order to produce another array.
Example :
- @net_name = (“dvdd”, “dvdd_pll”, “DVSS”, “vss”, “signal1”, “sig2”);
- print “1. @net_name\n”;
- @ground_nets = @net_name[2,3];
- print “@ground_nets\n”;
- Output:
- 1. dvdd dvdd_pll DVSS vss signal1 sig2
- DVSS vss
Range operator(..)
- Example for range operator(..):
- @net_name = (“dvdd”, “dvdd_pll”, “DVSS”, “vss”, “signal1”, “sig2”);
- print “1. @net_name\n”;
- @ground_nets = @net_name[2..5];
- print “@ground_nets\n”;
- Output:
- 1. dvdd dvdd_pll DVSS vss signal1 sig2
- DVSS vss signal1 sig2
Replacing Array Elements
Now we are going to introduce one more function called splice(), which has the following syntax −
Splice @ARRAY, OFFSET [ , LENGTH [ , LIST ] ];
This function will remove the elements of @ARRAY designated by OFFSET and LENGTH, and replaces them with LIST, if specified. Finally, it returns the elements removed from the array. Following is the example −
@nums = (1..20);
print “Before – @nums\n”;
splice(@nums, 5, 5, 21..25);
print “After – @nums\n”;
OUTPUT:
Before – 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
After – 1 2 3 4 5 21 22 23 24 25 11 12 13 14 15 16 17 18 19 20
Transform Strings to Arrays
•Let’s look into one more function called split(), which has the following syntax −
•Split [ PATTERN [ , EXPR [ , LIMIT] ] ]
•This function splits a string into an array of strings and returns it. If LIMIT is specified, splits into at most that number of fields. If PATTERN is omitted, splits on whitespace. Following is the example −
•Define the string
•$organization = “VLSITUTOR software technology pvt ltd”;
•@org_list = split (‘ ‘, $organization);
•print “@org_list\n”;
•print “$org_list[2]\n”;
•Output :
•VLSITUTOR software technology pvt ltd
•technology
Sorting Arrays
•The sort() function sorts each element of an array according to the ASCII Numeric standards.
•Syntax: sort [SUBROUTINE] LIST
•
•# define an array
•@foods = qw(pizza steak chicken burgers);
•print “Before: @foods\n”;
•# sort this array @foods = sort(@foods);
•print “After: @foods\n”;
•Output:
•Before: pizza steak chicken burgers
•After: burgers chicken pizza steak
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..
Examples
- %data = (‘power’ => 45, ‘ground’ => 30, ‘signal’ => 40);
- print “$data{‘power’}\n”;
- print “$data{‘ground’}\n”;
- print “$data{‘signal’}\n”;
Output:
- 45
- 30
- 40
Extracting Keys and Values
- we can get a list of all of the keys from a hash by using keys function, which has the following syntax “keys%HASH”
- Similarly, Can use values function to get a list of all the values. This function has the following syntax −”values %HASH”
Example :
%data = (‘power’ => 45, ‘ground’ => 30, ‘signal’ => 40);
@keynames = keys%data;
print “key names : @keynames\n”;
Output # power ground signal
@valuesnames = values %data;
print “values of data: @valuesnames\n”;
Output # 45 30 40
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.
- If : A Perl if statement consists of a boolean expression followed by one or more statements.
- If..else: An if statement can be followed by an optional else statement.
- If ..elsif..else:: An if statement can be followed by an optional elsif statement and then by an optional else statement.
Syntax:
if(boolean_expression 1) {
# Executes when the boolean expression 1 is true
} elsif( boolean_expression 2) {
# Executes when the boolean expression 2 is true
} else {
# Executes when the none of the above condition is true
}
Flow chart
conditional statements
Example:
$a = 100;
# check the boolean condition using if statement
if( $a == 20 ) {
# if condition is true then print the following
print “a has a value which is 20\n”;
} elsif( $a == 30 ) {
# if condition is true then print the following
print “a has a value which is 30\n”;
} else {
# if none of the above conditions is true
print “a has a value which is $a\n”;
}
Output: a has a value which is 100
Loop Statements
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 −
- While
- For
- Foreach
While loop
Repeats a statement or group of statements while a given condition is true. It tests the condition before executing the loop body.
Here statement(s) may be a single statement or a block of statements.
The condition may be any expression. The loop iterates while the condition is true. When the condition becomes false, program control passes to the line immediately following the loop
Example :
$a = 10;
# while loop execution
while( $a < 20 ) {
print “Value of a: $a\n”;
$a = $a + 1;
}
Flow diagram
Output
Value of a: 10
Value of a: 11
Value of a: 12
Value of a: 13
Value of a: 14
Value of a: 15
Value of a: 16
Value of a: 17
Value of a: 18
Value of a: 19
For loop
•A for loop is a repetition control structure that allows you to efficiently write a loop that needs to execute a specific number of times.
•The init step is executed first, and only once. This step allows you to declare and initialize any loop control variables. You are not required to put a statement here, as long as a semicolon appears.
•Next, the condition is evaluated. If it is true, the body of the loop is executed. If it is false, the body of the loop does not execute and flow of control jumps to the next statement just after the for loop.
•After the body of the for loop executes, the flow of control jumps back up to the increment statement. This statement allows you to update any loop control variables. This statement can be left blank, as long as a semicolon appears after the condition.
•The condition is now evaluated again. If it is true, the loop executes and the process repeats itself (body of loop, then increment step, and then again condition). After the condition becomes false, the for loop terminates.
Example
# for loop execution
for( $a = 10; $a < 20; $a = $a + 1 ) {
print “value of a: $a\n”;
}
Output
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19
Foreach Loop
- 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) {
…
}
example
•#!/usr/local/bin/perl
•@list = (2, 20, 30, 40, 50); # foreach loop execution
foreach $a (@list) {
print “value of a: $a\n”;
}
•Output:
•value of a: 2
•value of a: 20
•value of a: 30
•value of a: 40
Control statements
Next: The Perl next statement starts the next iteration of the loop. Causes the loop to skip the remainder of its body and immediately retest its condition prior to reiterating.
Syntax “next [lebel]”
Last: Terminates the loop statement and transfers execution to the statement immediately following the loop.
Syntax “next [lebel]”
Continue: A continue BLOCK, it is always executed just before the conditional is about to be evaluated again.
Redo: The redo command restarts the loop block without evaluating the conditional again. The continue block, if any, is not executed.
Syntax “redo [lebel]”
Flow diagram
Example
@list = (10..20);
foreach $v (@list){
if ($v == 14) {
next
}
print “the value of : $v\n”;
}
Output
- the value of : 10
- the value of : 11
- the value of : 12
- the value of : 13
- the value of : 15
- the value of : 16
- the value of : 17
- the value of : 18
- the value of : 19
- the value of : 20
LAST & Example
Last: Terminates the loop statement and transfers execution to the statement immediately following the loop.
@list = (10..20);
foreach $v (@list){
if ($v == 14) {
last;
}
print “the value of : $v\n”;
}
Output
- the value of : 10
- the value of : 11
- the value of : 12
- the value of : 13
Continue
Continue: A continue BLOCK, it is always executed just before the conditional is about to be evaluated again.
@list = (1, 2, 3, 4, 5);
foreach $a (@list) {
print “Value of a = $a\n”;
} continue {
last if $a == 4;
}
Output:
- Value of a = 1
- Value of a = 2
- Value of a = 3
- Value of a = 4
Redo
@list = (1..10);
foreach $v (@list){
if ($v == 4) {
redo;
}
print “the value of : $v\n”;
}
the value of : 1
the value of : 2
the value of : 3
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 Arithmetic Operators
- + ( Addition )
- Adds values on either side of the operator
- Example − $a + $b will give 30
- – (Subtraction)
- Subtracts right hand operand from left hand operand
- Example − $a – $b will give -10
- * (Multiplication)
- Multiplies values on either side of the operator
- Example − $a * $b will give 200/ (Division)
- Divides left hand operand by right hand operand
- Example − $b / $a will give 2
- % (Modulus)
- Divides left hand operand by right hand operand and returns remainder
- Example − $b % $a will give 0
- ** (Exponent)
- Performs exponential (power) calculation on operators
- Example − $a**$b will give 10 to the power 20
Examples
- # Operands
- $a = 10;
- $b = 4;
- # using arithmetic operators
- print “Addition is: “, $a + $b, “\n”;
- print “Subtraction is: “, $a – $b, “\n”;
- print “Multiplication is: “, $a * $b, “\n”;
- print “Division is: “, $a / $b, “\n”;
- print “Modulus is: “, $a % $b, “\n”;
- print “Exponent is: “, $a ** $b, “\n”;
Output
- Addition is: 14
- Subtraction is: 6
- Multiplication is: 40
- Division is: 2.5
- Modulus is: 2
- Exponent is: 10000
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 −
•== (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.
•!= (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.
•<=>
•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
> (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.
< (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.
>= (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.
<= (less than or equal to)
Checks if the value of left operand is less than or equal to the value of right operand, if yes then condition becomes true.
Example − ($a <= $b) is true.
Examples
- $a = 10;
- $b = 60;
- # using Relational Operators
- if ($a == $b){
- print “Equal To Operator is True\n”;
- }else{
- print “Equal To Operator is False\n”;
- }
- Output: Equal To Operator is False
- if ($a != $b){
- print “Not Equal To Operator is True\n”;
- }else{
- print “Not Equal To Operator is False\n”;
- }
- Output: Not Equal To Operator is True
- if ($a > $b){
- print “Greater Than Operator is True\n”;
- }else{
- print “Greater Than Operator is False\n”;
- }
- Output: Greater Than Operator is False
- if ($a < $b){
- print “Less Than Operator is True\n”;
- }else{
- print “Less Than Operator is False\n”;
- }
- Output: Less Than Operator is True
- if ($a <=> $b){
- print “Comparison of Operator is True\n”;
- }else{
- print “Comparison of Operator is False\n”;
- }
- Output: Comparison of Operator is True
Perl String Equality Operators Example
- lt(less than )
- Returns true if the left argument is stringwise less than the right argument.
- Example − ($a lt $b) is true.
- gt(greater than )
- Returns true if the left argument is stringwise greater than the right argument.
- Example − ($a gt $b) is false.
- le(less than or equal )
- Returns true if the left argument is stringwise less than or equal to the right argument.
- Example − ($a le $b) is true.
- ge(greater than or equal )
- Returns true if the left argument is stringwise greater than or equal to the right argument.
- Example − ($a ge $b) is false.
- eq(equal)
- Returns true if the left argument is stringwise equal to the right argument.
- Example − ($a eq $b) is false.
- ne(not equal)
- Returns true if the left argument is stringwise not equal to the right argument.
- Example − ($a ne $b) is true.
- cmp
- Returns -1, 0, or 1 depending on whether the left argument is stringwise less than, equal to, or greater than the right argument.
- Example − ($a cmp $b) is -1.
- #!/usr/local/bin/perl
- $a = “abc”;
- $b = “xyz”;
- print “Value of \$a = $a and value of \$b = $b\n”;
- if( $a lt $b ) {
- print “$a lt \$b is true\n”;
- } else {
- print “\$a lt \$b is not true\n”;
- }
- Output: abc lt $b is true
- if( $a gt $b ) {
- print “\$a gt \$b is true\n”;
- } else {
- print “\$a gt \$b is not true\n”;
- }
- Output: $a gt $b is not true
- if( $a le $b ) {
- print “\$a le \$b is true\n”;
- } else {
- print “\$a le \$b is not true\n”;
- }
- Output: $a le $b is true
- if( $a ge $b ) {
- print “\$a ge \$b is true\n”;
- } else {
- print “\$a ge \$b is not true\n”;
- }
- Output: $a ge $b is not true
- if( $a ne $b ) {
- print “\$a ne \$b is true\n“
- ;} else {
- print “\$a ne \$b is not true\n”;
- }
- Output :$a ne $b is true
- $c = $a cmp $b;
- print “\$a cmp \$b returns $c\n”;
- Output : $a cmp $b returns -1
Perl Assignment Operators
- =
- 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
- +=
- 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
- -=
- 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
- *=
- 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
- /=
- 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
- %=
- 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
Examples
•#!/usr/local/bin/perl
•$a = 10;
•$b = 20;
•print “Value of \$a = $a and value of \$b = $b\n”;
•Output: Value of $a = 10 and value of $b = 20
•$c = $a + $b;
•print “After assignment value of \$c = $c\n”;
•Output: After assignment value of $c = 30
•$c += $a;
•print “Value of \$c = $c after statement \$c += \$a\n”;
•Output: Value of $c = 40 after statement $c += $a
•$c -= $a;
•print “Value of \$c = $c after statement \$c -= \$a\n”;
•Output: Value of $c = 30 after statement $c -= $a
•$c *= $a;
•print “Value of \$c = $c after statement \$c *= \$a\n”;
•Output: Value of $c = 300 after statement $c *= $a
•$c /= $a;
•print “Value of \$c = $c after statement \$c /= \$a\n”;
•Output: Value of $c = 30 after statement $c /= $a
•$c %= $a;
•print “Value of \$c = $c after statement \$c %= \$a\n”;
•Output: Value of $c = 0 after statement $c %= $a
•$c = 2;
•$a = 4;
•print “Value of \$a = $a and value of \$c = $c\n”;
•Output: Value of $a = 4 and value of $c = 2
•$c **= $a;
•print “Value of \$c = $c after statement \$c **= \$a\n”;
•Output: Value of $c = 16 after statement $c **= $a
Perl Bitwise Operators
- &
- Binary AND Operator copies a bit to the result if it exists in both operands.
- Example − ($a & $b) will give 12 which is 0000 1100
- |
- Binary OR Operator copies a bit if it exists in eather operand.
- Example − ($a | $b) will give 61 which is 0011 1101
- ^
- Binary XOR Operator copies the bit if it is set in one operand but not both.
- Example − ($a ^ $b) will give 49 which is 0011 0001
- ~
- Binary Ones Complement Operator is unary and has the efect of ‘flipping’ bits.
- Example − (~$a ) will give -61 which is 1100 0011 in 2’s complement form due to a signed binary number.
- <<
- Binary Left Shift Operator. The left operands value is moved left by the number of bits specified by the right operand.
- Example − $a << 2 will give 240 which is 1111 0000
- >>
- Binary Right Shift Operator. The left operands value is moved right by the number of bits specified by the right operand.
- Example − $a >> 2 will give 15 which is 0000 1111
Examples
- $a = 60;
- $b = 13;
- print “Value of \$a = $a and value of \$b = $b\n”;
- $c = $a & $b;
- print “Value of \$a & \$b = $c\n”;
- $c = $a | $b;
- print “Value of \$a | \$b = $c\n”;
- $c = $a ^ $b;
- print “Value of \$a ^ \$b = $c\n”;
- $c = ~$a;
- print “Value of ~\$a = $c\n”;
- $c = $a << 2;
- print “Value of \$a << 2 = $c\n”;
- $c = $a >> 2;print “Value of \$a >> 2 = $c\n”;
- Ouput:
- Value of $a = 60 and value of $b = 13
- Value of $a & $b = 12
- Value of $a | $b = 61
- Value of $a ^ $b = 49
- Value of ~$a = 18446744073709551555
- Value of $a << 2 = 240
- Value of $a >> 2 = 15
Perl Logical Operators
•and
•Called Logical AND operator. If both the operands are true then then condition becomes true.
•Example − ($a and $b) is false.
•&&
•C-style Logical AND operator copies a bit to the result if it exists in both operands.
•Example − ($a && $b) is false.
•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.
Operators
•||
•C-style Logical OR operator copies a bit if it exists in eather operand.
•Example − ($a || $b) is true.
•not
•Called Logical NOT Operator. Use to reverses the logical state of its operand. If a condition is true then Logical NOT operator will make false.
•Example − not($a and $b) is true.
•$a = true;
•$b = false;
•print “Value of \$a = $a and value of \$b = $b\n”;
•$c = ($a and $b);
•print “Value of \$a and \$b = $c\n”;
•$c = ($a && $b);
•print “Value of \$a && \$b = $c\n”;
•$c = ($a or $b);
•print “Value of \$a or \$b = $c\n”;
$c = ($a || $b);
print “Value of \$a || \$b = $c\n”;
$a = 0;
$c = not($a);
print “Value of not(\$a)= $c\n”;
Output:
Value of $a = true and value of $b = false
Value of $a and $b = false
Value of $a && $b = false
Value of $a or $b = true
Value of $a || $b = true
Value of not($a)= 1
Quote-like Operators
•q{ }
•Encloses a string with-in single quotes
•Example − q{abcd} gives ‘abcd’
•qq{ }
•Encloses a string with-in double quotes
•Example − qq{abcd} gives “abcd”
•qx{ }
•Encloses a string with-in invert quotes
•Example − qx{abcd} gives `abcd`
Examples
- $a = 10;
- $b = q{a = $a};
- print “Value of q{a = \$a} = $b\n”;
- $b = qq{a = $a};
- print “Value of qq{a = \$a} = $b\n”;
- # unix command execution
- $t = qx{date};
- print “Value of qx{date} = $t\n”;
Output
- Value of q{a = $a} = a = $a
- Value of qq{a = $a} = a = 10
- Value of qx{date} = Tue Nov 22 10:44:09 UTC 2022
Miscellaneous Operators
.
Binary operator dot (.) concatenates two strings.
Example − If $a = “abc”, $b = “def” then $a.$b will give “abcdef”
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 —.
..
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)
Operators
•++
•Auto Increment operator increases integer value by one
•Example − $a++ will give 11
•—
•Auto Decrement operator decreases integer value by one
•Example − $a– will giv
•->
•The arrow operator is mostly used in dereferencing a method or variable from an object or a class name
•Example − $obj->$a is an example to access variable $a from object $obj.
Output
•#!/usr/local/bin/perl
•$a = “abc”;
•$b = “def”;
•$c = $a . $b;
•print “Value of \$a . \$b = $c\n”;
•Output: Value of $a . $b = abcdef
•$c = “-” x 3;
•print “Value of \”-\” x 3 = $c\n”;
•Output: Value of “-” x 3 = —
•@c = (2..5);
•print “Value of (2..5) = @c\n”;
•Output: Value of (2..5) = 2 3 4 5
•$a = 10;
•$b = 15;
•$a++;
•$c = $a ;
•print “Value of \$a after \$a++ = $c\n”;
•Output: Value of $a after $a++ = 11
•$b–;
•$c = $b ;
•print “Value of \$b after \$b– = $c\n”;
•Output: Value of $b after $b– = 14
Subroutines
- A Perl subroutine or function is a group of statements that together performs a task. You can divide up your code into separate subroutines. How you divide up your code among different subroutines is up to you, but logically the division usually is so each function performs a specific task.
- Perl uses the terms subroutine, method and function interchangeably.
- Define and Call a Subroutine: Syntax
“sub subroutine_name {
body of the subroutine
}
Subroutine_name( list of arguments );” #calling function
Sub basic example
#!/usr/bin/perl
# Function definition
sub Hello {
print “Hello, World!\n”;
}
Hello(); # Function call
Output:
Hello, world!
Passing Arguments to a Subroutine
- You can pass various arguments to a subroutine like you do in any other programming language and they can be accessed inside the function using the special array @_.
- Thus the first argument to the function is in $_[0], the second is in $_[1], and so on.
#!/usr/bin/perl
# Function definition
sub PrintList {
my @list = @_;
print “Given list is @list\n”;
}
$a = 10;
@b = (1, 2, 3, 4);
# Function call with list parameter
PrintList($a, @b);
Given list is 10 1 2 3 4
#!/usr/bin/perl
# Function definition
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);
age : 19
name : Tom
Filehandle
The basics of handling files are simple: you associate a filehandle with an external entity (usually a file) and then use a variety of operators and functions within Perl to read and update the data stored within the data stream associated with the filehandle.
A filehandle is a named internal Perl structure that associates a physical file with a name. All filehandles are capable of read/write access, so you can read from and update any file or device associated with a filehandle. However, when you associate a filehandle, you can specify the mode in which the filehandle is opened.
Three basic file handles are – STDIN, STDOUT, and STDERR, which represent standard input, standard output and standard error devices respectively.
Mode for filehandle
•< or r
•Read Only Access
•> or w
•Creates, Writes, and Truncates
•>> or a
•Writes, Appends, and Creates
•+< or r+
•Reads and Writes
•+> or w+
•Reads, Writes, Creates, and Truncates
•+>> or a+
•Reads, Writes, Appends, and Creates
Opening and Closing Files
•open FILEHANDLE, EXPRopen
•FILEHANDLE
•Here FILEHANDLE is the file handle returned by the open function and EXPR is the expression having file name and mode of opening the file.
•#!/usr/bin/perl
•open(DATA, “<file.txt”) or die “Couldn’t open file file.txt, $!”;
•while(<DATA>) {
• print “$_”;
•}
•close (DATA);
•Output :
•Couldn’t open file file.txt, No such file or directory at main.pl line
Regular Expressions
- A regular expression is a string of characters that defines the pattern or patterns you are viewing. The syntax of regular expressions in Perl is very similar to what you will find within other regular expression. Supporting programs, such as sed, grep, and awk.
- The basic method for applying a regular expression is to use the pattern binding operators =~ and !~. The first operator is a test and assignment operator.
- There are three regular expression operators within Perl.
- Match Regular Expression – m//
- Substitute Regular Expression – s///
- Transliterate Regular Expression – tr///
- The match operator, m//, is used to match a string or statement to a regular expression.
- 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; and $’, which contains everything after the matched string.
Regular Expressions
•#!/usr/bin/perl
•$string = “The food is in the salad bar”;
•$string =~ m/foo/;
•print “Before: $`\n”;
•print “Matched: $&\n”;
•print “After: $’\n”;
•Before: The
•Matched: foo
•After: d is in the salad bar
Substitution Operator
- The substitution operator, s///, is really just an extension of the match operator that allows you to replace the text matched with some new text. The basic form of the operator is −
- s/PATTERN/REPLACEMENT/;
- The PATTERN is the regular expression for the text that we are looking for. The REPLACEMENT is a specification for the text or regular expression that we want to use to replace the found text with.
- $string = “the power net name is vdd”;
- $string =~ s/vdd/dvdd/;
- print “$string\n”;
- the power net name is dvdd
Translation Operator
- tr/SEARCHLIST/REPLACEMENTLIST/
- The translation replaces all occurrences of the characters in SEARCHLIST with the corresponding characters in REPLACEMENTLIST.
- The /d modifier deletes the characters matching SEARCHLIST that do not have a corresponding entry in REPLACEMENTLIST.
- The last modifier, /s, removes the duplicate sequences of characters that were replaced.
Example
•#/user/bin/perl
•$string = “The cat sat on the mat”;
•$string =~ tr/a/o/;
•print “$string\n”;
•Output:
•The cot sot on the mot
More Complex Regular Expressions^
- ^
- Matches beginning of line.
- $
- Matches end of line.
- .
- Matches any single character except newline. Using m option allows it to match newline as well.
- […]
- Matches any single character in brackets
- [^…]
- Matches any single character not in brackets.
- *
- Matches 0 or more occurrences of preceding expression.
- +
- Matches 1 or more occurrence of preceding expression.
- ?
- Matches 0 or 1 occurrence of preceding expression.
- {n}
- Matches exactly n number of occurrences of preceding expression.
- { n, m}
- Matches at least n and at most m occurrences of preceding expression
- a| b
- Matches either a or b.
- \W
- Matches nonword characters.
- \s
- Matches whitespace. Equivalent to [\t\n\r\f].
- \S
- Matches nonwhitespace.
- \d
- Matches digits. Equivalent to [0-9].
- \D
- Matches nondigits.
- \A
- Matches beginning of string.