Let’s put it in a simple manner. While computers understand just 0’s and 1’s (binary language/machine language/ [low-level language]), it is very difficult to program in a binary language for us human. Perl is a programming language which uses natural language elements, words that are used in common English language and is, therefore, easier to understand by humans [high-level language]. Now there’s a problem; computers cannot understand high-level languages, which we humans can easily understand. For that, we need something which can translate the high-level language to low-level language. Here interpreter comes to our help. The interpreter is a piece of software which converts the program written in the high-level language to low-level language for the computer to understand and execute the instructions written in the program. Hence, Perl is an interpreted programming language.

Where is Perl used?

The power of Perl scripting language can be implemented in many fields. The most popular use of Perl is in Web development., Perl is also used to automate many tasks in the Web servers, and other administration jobs, it can automatically generate emails and clean up systems. Perl is still used for its original purpose i.e. extracting data and generating reports. It can produce reports on resource use and check for security issues in a network. Due to this reason, Perl has become a popular language used in web development, networking and bioinformatics too. Apart from all this perl can also be used for CGI programming. Perl can also be utilized for image creation & manipulation. Apart from that networking via telnet, FTP, etc., Graphical User Interface creation, VLSI electronics & to create mail filters to reduce spamming practices are some use cases of Perl. Perl is also known for implementation of OOP(object oriented programming) practices and supports all forms of inheritance (simple, multiple & diamond), polymorphism and encapsulation. Perl is flexible enough to support Procedural as well as OOP practices simultaneously. Perl also has extra modules which permit you to write or use/reuse code written in Python, PHP, PDL, TCL, Octave, Java, C, C++, Basic, Ruby and Lua in your Perl script. This means that you can combine Perl with these extra programming languages rather rewriting existing code.

Why use Perl?

It is true that there are other programming languages that can be used to do all the stuff that has been stated above, then why should you specifically use Perl? Perl is very easy to learn, especially if you have a background in computer programming. Perl was designed to be easy for humans to write and understand rather than making it easy for processing by computers. It uses regular expressions. It’s natural style of language is different from other programming languages that use specific grammar and syntaxes; therefore, Perl is very flexible and doesn’t impose on you any particular way of thinking out a solution or a problem. Perl is extremely portable. It can run on any operating system that has Perl interpreter installed, so it is platform independent. All Linux Operating Systems come installed with Perl, so you can start Perl coding in Linux out of the box. This is unlike Shell scripts, where the code changes with the flavor of Linux distribution being used, making it less and less portable Small specific tasks in Perl become very easy and quick. Throughout this Perl tutorial for beginners, you will learn how you can code small, quick programs for specific tasks. Let’s take a simple example of the classic Hello World program which is used to begin learning any programming language which has UNIX as its roots:

Example: Perl hello world

Output: Hello, world! The above two lines of code will print Hello, world! Now wasn’t it too simple and quick? Students with knowledge of C, C++ will know that it requires many more lines of code to obtain the same output in those languages.
You might be wondering why Perl is so famous on the Web. It is simple as most of the things that happen on the web are of TEXT and Perl is very good at text processing. If we compare Perl with any of the languages, then Perl will be the best language which is good in File handling, text processing, and output reporting One of the best advantages of Perl is that it is free to use The Perl community strongly believes that software should be freely available, freely modifiable and freely distributable. Several volunteers from Perl community strive to make the programming language as good as possible.

Advantages and Disadvantages of Perl

Let’s get started

With enough knowledge about the history of Perl and basic concepts of computer programming required for coding in Perl, it is time we take the dive and get started with Perl. The next chapter will teach you how you can setup Perl on your system and get ready for the coding journey in Perl. This Perl scripting tutorial will take Linux as the OS which students will be using for coding in Perl.

Download & Install Perl – Windows, Mac & Linux

How to get Perl?

Good news you probably have it! But if you can’t find it already on your system, you can still get it for free. To find out if you already have Perl installed, go into the command line and type: perl -v

The command will display version of Perl if it’s installed. In this case, the version is v5.14.2. But if not… don’t panic…

Updating Perl on Linux:

If you need to update the Perl version then just enter one single line of command sudo apt-get install perl and relax. The rest will be taken care of. Just make sure you have an active internet connection.

Install perl for Windows:

First, download the Active Perl from this link. Follow these steps to install ActivePerl on Windows system. See the below screenshots for the same. Step 1: Once you download the installer and start the installation you will see the below window, click on next to proceed.

Step 2: Accept Licensing agreement to proceed the installation.

Step 3: Below are different packages that will be installed. By default, all will be selected. The only thing different is PPM (Perl Package Manager). This is the utility provided by Active Perl to install external Perl modules or libraries in your system. Click on Next to proceed.

Step 4: These are different types of Perl extensions that can be used for Perl. Mostly we will be using .Pl, .Plx and .Pm for Perl. Perl modules basically use .Pm as their file extension to refer to a library file. Select all the options and click on the Next button.

Step 5: Click on Install button to proceed with the installation.

Step 6: Once installed, execute the command ‘Perl –v’ to check whether Perl is successfully installed in your system.

There are lots of things which needs to be discussed for setting Perl environment in both Linux and Windows, as there won’t be many library files included in this installation. You need to manually install those. You can install those manually using CPAN(Comprehensive Perl Archive Network) or either PPM which works only for perl windows. But these files are not mandatory to start coding in Perl. Apart from this windows setup you could use Windows 10’s new feature of Linux subsystem over windows & use it for running perl code First Perl Program

Perl Example: Hello World

Don’t worry if you don’t understand this text. Everything will be clear soon. Come on and take a look at it by line: This tells the Operating System to execute this file with the program located at /usr/bin/perl Some IDEs don’t need this line. If it’s essential, you must write here a path to your interpreter. Remember! This special line must be at the beginning of your program and must starts from #! use warnings; This is another special command which tells the interpreter to display any warnings i.e. -w which activates warnings globally. The print instruction writes text to the screen. The semicolon at the end of the line tells the perl interpreter that the instruction is finished. You must put a semicolon at the end of every instruction in Perl code. Note the quotation mark(“). It’s necessary for print instruction. Save the above script as firstprog.pl

On Windows

If you have Strawberry installed, you can simply click on Run. You can also run command-line interface and write on the console: or, if perl.exe is not in your path:

On Linux/Unix

You just have to open the Terminal and write: If you can’t run the program, make sure you have eligibility to run it. Type in the Terminal: Your program is now executable and ready to run. To execute, write:

Install cpan minus modules

Modules are set of codes that are used to do tasks that perform common operations in several programs. If you use perl modules, you do not have to rewrite the codes to perform that same operation. Perl can make use of such external libraries of codes. One of the best libraries is the CPAN. It stands for Comprehensive Perl Archive Network and contains a vast amount of Perl modules for you to use. It is a community or network of a large number of developers who contribute such modules. By installing support for CPAN modules in your perl module, you can make use of the CPAN modules and make your work easier. Most Perl modules are written in Perl, some use XS (they are written in C) so require a C compiler (it’s easy to get this setup – don’t panic. Modules may have dependencies on other modules (almost always on CPAN) and cannot be installed without them (or without a specific version of them). It is worth thoroughly reading the documentation for the options below. Many modules on CPAN now require a recent version of Perl (version 5.8 or above). Install cpanminus a script to get, unpack, build and install modules from CPAN to make installing other modules easier (you’ll thank us later). To Install App-cpanminus perl modules, in the command line type: cpan App::cpanminus Make sure you have internet connection while perl modules are being downloaded and installed.

Now install any module: Let’s see an example of installing a module File::Data(It’s an Interface to access File Data).

Perl Variable

Now, we’ll talk about variables. You can imagine variable like kind of container which holds one or more values. Once defined, the name of variable remains the same, but the value or values change over and over again.

There are 3 Types of variables:

The easiest ones are scalars, and this is ours today subject

Scalar Variable

This type of variable holds a single value. Its name begins with a dollar sign and a Perl identifier (it’s the name of our variable).

Naming Convention

If you are familiar with other programming languages, then you would know that there are certain rules about naming variables. Similarly, Perl has three rules for naming scalars.

All scalar names will begin with a $. It is easy is to remember to prefix every name with $. Think of it as a $scalar. 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““ 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. Those coming from C/C++ background should be immediately able to recognize the similarity. Examples

Perl Example: These, however, are not legal scalar variable names. The general rule says, when Perl has just one of something, that’s a scalar. Scalars can be read from devices, and we can use it to our programs.

Two Types of Scalar Data Types

Numbers Strings

Numbers:

In this type of scalar data we could specify:

integers, simply it’s whole numbers, like 2, 0, 534 floating-point numbers, it’s real numbers, like 3.14, 6.74, 0.333

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

Integer literals:

It consists of one or more digits, optionally preceded by a plus or minus and containing underscores. Perl Examples: As you can see- it’s nothing special. But believe me, this is the most common type of scalars. They’re everywhere.

Floating-point literals:

It consists of digits, optionally minus, decimal point and exponent. Perl Examples:

Octal, Hexadecimal and Binary representation:

It’s alternative to the decimal system. Allow me to show you Octal, Hexadecimal and Binary representation. A short table presents all important information about this weird styles: Perl Examples: All of these values for Perl means the same. Perl doesn’t store the values in the same format. It will internally convert these hexadecimal, binary, octal to decimal values. The assignment is the most common operation on a scalar, and it’s very simple. Perl uses for that equal sign. It takes a value of the expression from the right side and puts this value to our variable. Let’s take a look to examples: What’s more you can put in variable not only a number, but also an expression.

Strings

Strings: It’s also very simple type of scalar. 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. Perl programs can be written entirely in 7-bit ASCII character set. Perl also permits you to add any 8-bit or 16-bit character set aka. non-ASCII characters within string literals. Perl has also added support for Unicode UTF-8.

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 you want to be taken literally. A short example and everything should be clear: Perl Examples: Output: it is $num Here due to single quotes value of $num in not taken and the literal characters ‘$’,’n’, ‘u’ & ‘m’ are added to the value of $txt

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. Perl Examples: Output: it is 7 Here due to double quotes value of $num is taken added to the value of $txt Double-quotes interpolate scalar and array variables, but not hashes. On the other hand, you can use double-quotes to interpolate slices of both arrays and hashes. Mysterious \n Consider the following program Perl Examples: Output: hello Perl does not display just ‘hello\n’, but only ‘hello’. Why? Because ‘\n’ is a special sign and means that you want to go to a new line while displaying the text in your program. print “hello\n new line”; Next question- are there any other special sign? Yes, they are! But don’t worry- just a few. Check the table below I know, there isn’t ‘just a few’… But believe me, you must to know just

Strings Variable

It’s the same operation, which we see in numbers assignment. Perl gets our string from the right side of the equal sign and puts this string to a variable. Perl Examples: Output: tutorial315 As you can see, you can put numbers and strings in the same variables. There isn’t class of variables.

String Concatenation (period) :

The concatenation operator “.” unites two or more strings. Remember! If the string contains quotes, carriage returns, backslashes, all these special characters need to be escaped with a backslash. Perl ‘ ‘ variable Examples: Output: Tom is mother’s favorite cat The strings “$a”, “$b”, is concatenated & stored in “$c” using the “.” operator. In the end…

Conversion Between Numbers and Strings:

As you know, Perl automatically converts between numbers to string as needed. How does Perl know, what we need right now? This is simple- everything depends on the operator (we’ll talk about operators later, now, just accept there are a lot of operators, different for numbers and strings) If an operator expects a number, Perl will use the value as a number. If an operator expects a string, Perl will use the value as a string. In other words- you don’t need to worry about this kind of conversion. Short example and everything should be clear: Perl Examples: Output: 71 the value of $string is converted to an integer and added to the value of $number. The result of the addition, 71, is assigned to $result. 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

my local our

My: Using this you can declare any variable which is specific within the block. i.e. within the curly braces. No Output The output of the program will be nothing!

In the above example, you will see that there are two variables declared one is inside if block ($var_2) and the other is outside the If block ($var). The variable, which is declared outside the block will be accessible to if block but the variable which was declared inside if block won’t be accessible to the outer program. Local: Using this we can actually mask the same variable values to different values without actually changing the original value of the variable, suppose we have a variable $a for which the value is assigned 5, you can actually change the value of that variable by re-declaring the same variable using local keyword without altering the original value of the variable which is 5. Let’s see how this works with an example. The output of the above program will be in this manner. local, $var = 3 global, $var = 5 This way we can change the value of the variable without affecting the original value. Our: Once a variable is declared with access modifier “our” it can be used across the entire package. Suppose, you have Perl module or a package test.pm which has a variable declared with scope our. This variable can be accessed in any scripts which will use that package. If you are serious about programming in Perl, you should begin your program with #!/usr/local/bin/perl

use strict;

This will help you write better and cleaner code. ‘use strict’ turns on strict pragma which will make you declare your variables with my keyword. This is a good programming practice Result: Error Output: 10

Perl Array

What is Perl Array?

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. This looks great, So how do we create an array in Perl? 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; This is how we define an array in Perl; you might be thinking how we need to store data in it. There are different ways of storing data in an array. This depends on how you are going to use it. Output: abcd This is an array with 4 elements in it. The array index starts from 0 and ends to its maximum declared size, in this case, the max index size is 3. You can also declare an array in the above way; the only difference is, it stores data into an array considering a white space to be the delimiter. Here, qw() means quote word. The significance of this function is to generate a list of words. You can use the qw in multiple ways to declare an array. Output: abcdpqrsvxyz Suppose you want to assign a value to the 5th element of an array, how are we going to do that. $array [4] =’e’;

Sequential Array

Sequential arrays are those where you store data sequentially. Suppose, you want to store 1-10 numbers or alphabets a-z in an array. Instead of typing all the letters, you can try something like below – Output: 12345678910

Perl Array Size

We have an array which is already available, and you don’t know what the size of that array is, so what is the possible way to find that. Can we get the size of an array without using functions? Yes, we can. Output: 5 5

Dynamic Array

The above method of declaring an array is called static arrays, where you know the size of an array. What is Dynamic Array? Dynamic arrays are those that you declare without specifying any value on them. So when exactly do we store values in that array? Simple, we store them during run time. Here is a simple program for that. We will be using some inbuilt Perl functions for doing this task. Output: This is kind of dyn mic rr y The split function splits the content of string into an array based on the delimiter provided to it. This function will also eliminate the delimiter from the string, in this case, it is ‘a’;

Push, Pop, shift, unshift for Perl arrays:

These functions can be used in Perl to add/delete to array elements.

Perl Push: adds array element at the end of an existing array. Perl Pop: removes the last element from an array. Perl Shift: removes the first element from an array. Perl Unshift: adds an element at the beginning of an array.

Let’s see an example where we can use the below functions.

Output: 1st : Mon Tue Wed 2nd when push : Mon Tue Wed Thu 3rd when unshift : Fri Mon Tue Wed Thu 4th when pop : Fri Mon Tue Wed 5th when shift : Mon Tue Wed

Perl Hashes

Why do we need Hash?

We already learned about scalars and arrays in previous sections. What exactly scalars do? It only stores integers and strings. What exactly arrays do? It is a collection of scalars, where you access each element of an array using indices. But, is this good idea to use an array when you have hundreds and thousands of records? We will forget which index has what value. To overcome this situation we have something like perl hash.

What are Hashes?

A hash can also hold as many scalars as the array can hold. The only difference is we don’t have any index rather we have keys and values. A hash can be declared, starting with % followed by the name of the hash. Let’s see an example how we can define a Perl hash and how we can differentiate this from array Consider an example of three people and their ages are represented in an array. Output: Sainath33Krishna24Shruthi25 This way it is difficult to know individual ages as we need to remember both index locations of name and age of all the people. It may be simple when you have 3 names, but when you have 1000 or more? You know the answer.

This we can overcome using a hash. Hash Example: Output: Sainath33Krishna24Shruthi25Sainath33Krishna24Shruthi25 We have now declared a hash, great!! But, how do we access or print it? Each element in hash should be accessed with its associated key for which there will be a value assigned. So, there is a one-one mapping between each of the key and value in the hash. In order to print the age of any person, you just need to remember the name of that person. You might have wondered why I used $hash{KeyName}, remember a hash is a collection of scalars again. So, we can use $ which represents scalar to access each hash element.

Note: Each Key in hash should be unique or else it will override your value, which was assigned previously. How can we assign a hash to another hash? Simple, same way as we do for We can also print entire hash. Output: Tom23

Add Perl Hashes

As you can see we already have a hash %newHash, and now we need to add more entries into it. Output: Jim25John26Harry27

Perl Delete key

You may want to delete an entry from a hash. This is how we can do that. Delete is an inbuilt function of Perl. Here, we will see an example of assigning a hash to an array. Note: Whenever you print a hash or when you store hash into an array. The order may always differ. It’s not the same always. We can assign only keys or values of a hash to an array. To remove all the entries in the hash, we can directly assign the hash to null. %newHash=();# This will redefine the hash with no entries.

Perl Conditional Statements

We can use conditional Statements in Perl. So, what are conditional statements? Conditional statements are those, where you actually check for some circumstances to be satisfied in your code. Think about an example, you are buying some fruits, and you don’t like the price to be more than 100 bucks. So, the rule here is 100 bucks. Perl supports two types of conditional statements; they are if and unless.

Perl If

If code block will be executed, when the condition is true.

Output: 5

Perl If Else

This looks good. Let us think about a situation where $a is not 5. Output: The value is 10 —FAIL This way we can control only one condition at a time. Is it a limitation? No, you can also control various conditions using if… elsif … else.

Perl Else If

Output: Executed elsif block –The value is 5 In the above case, the elsif block will be executed as $a is equal to 5. There could be situations where both if and elsif code blocks will be failed. In this scenario, the else code block will be executed. You can actually eliminate the else code check if you don’t like to include.

Perl Nested If

In this case, you can use if code block in one more if code block. Output: Inside 1st else block – The value is 11 Execute the same code by change the value of $a; you can find out the rest.

Perl Unless

You have already got an idea what if does (If the condition is true it will execute the code block). Unless is opposite to if, unless code block will be executed if the condition is false. Output: Inside 1st else block – The value is 5 Guess what will be the output. You are right!!!!!. The output will be the print statement of the else block. Because of the condition in unless code block is true, remember unless block will be executed only if the condition is false. Change the value of $a and execute the code you will see the difference.

Perl Using if

Output: Inside else block

Using unless

Output: Inside unless Block

Perl Loops – Control Structures

Perl supports control structures similar to other programming languages. Perl supports four types of control structures for, foreach, while and until. We use these statements to, repeatedly execute some code.

For loop Perl

For code block will execute till the condition is satisfied. Let’s take an example of how to Perl loop an array. Output: The array index 0 value is 1 The array index 1 value is 2 The array index 2 value is 3 The array index 3 value is 4 The array index 4 value is 5 The array index 5 value is 6 The array index 6 value is 7 The array index 7 value is 8 The array index 8 value is 9 The array index 9 value is 10 Here, in for () expression, there are many statements included. There is a meaning for each of them.

for ( initialization ; condition; incrementing)

Here is another way of using for. Output: 1n 2n 3n 4n 5n 6n 7n 8n 9n 10n

Perl Foreach

The for each statement can be used in the same way as for; the main difference is we don’t have any condition check and incrementing in this. Let’s take the same example with foreach perl. Output: The value is 1 The value is 2 The value is 3 The value is 4 The value is 5 The value is 6 The value is 7 The value is 8 The value is 9 The value is 10 Foreach takes each element of an array and assigns that value to $var for every iteration. We can also use $_ for the same. Output: The value is 1 The value is 2 The value is 3 The value is 4 The value is 5 The value is 6 The value is 7 The value is 8 The value is 9 The value is 10 This looks good for accessing arrays. How about Hashes, how can we obtain hash keys and values using foreach? We can use foreach to access keys and values of the hash by looping it.

Output: Mickey Tom Jerry You might be wondering, Why we used Keys in foreach(). Keys is an inbuilt function of Perl where we can quickly access the keys of the hash. How about values? We can use values function for accessing values of the hash. Output: the value is 24 the value is 23 the value is 25

Perl While

The Perl While loop is a control structure, where the code block will be executed till the condition is true. The code block will exit only if the condition is false. Let’s take an example for Perl While loop.

Here is a problem, which will require input from the user and will not exit until the number provided as ‘7’. Output: Guess a Number Between 1 and 10 9 Guess a Number Between 1 and 10 5 Guess a Number Between 1 and 10 7 You guessed the lucky number 7 In the above example, the while condition will not be true if we enter input other than ‘7’. If you see how while works here, the code block will execute only if the condition in a while is true.

Perl do-while

Do while loop will execute at least once even if the condition in the while section is false. Let’s take the same example by using do while. Output: 10 9 8 7 6 5 4 3 2 1 Now value is less than 1

Perl until

Until code block is similar to unless in a conditional statement. Here, the code block will execute only if the condition in until block is false.
Let’s take the same example which we used in case of a while. Here is a problem, which will require input from the user and will not exit until the name provided as other than ‘sai’. Output: Enter any name sai

Perl do-until:

Do until can be used only when we need a condition to be false, and it should be executed at-least once. Output: Enter any name Howard Enter any name Sheldon Enter any name sai Execute while, do-while, until and do-until example codes to see the difference.

Perl Operator

What is Operator?

Operators in computer language indicate an action that can be performed on some set of variables or values which computer can understand. Perl has incorporated most of the Operators from C language. Perl has many operators compared with other programming languages. Operators are categorized as Arithmetic, Logical, relational and assignment operators. Arithmetic Operators: Arithmetic operators are those which can be used to perform some basic mathematic operations. These Arithmetic operators are binary operators where we need two arguments to perform a basic operation. We can also use unary operators for other basic operations; you can see the difference in examples below. Example to complete all the above operations. holding values $y=6; $z=$x+$y; $y=6; $z=$x-$y; $y=6; $z=$x*$y; $y=6; $z=$x/$y; Ex : 22 = 4, 33 = 27 $x=4; $y=2; $z=$x**$y; $x=10; $y=2; $z=$x % $y; $x++; Or ++$x; $x–; # post decrement Or –$x;# pre decrement Output: Add of 10 and 2 is 12 Sub of 10 and 2 is 8 Mul of 10 and 2 is 20 Div of 10 and 2 is 5 Exp of 10 and 2 is 100 Mod of 10 and 2 is 0

Assignment Operators:

Assignment operators simply assign values to variables, but there is one more thing which we need to remember here, assignment operators will also perform arithmetic operations and assign the new value to the same variable on which the operation is performed. Example to complete all the above operations. $x+=10; $x-=10; $x*=10; $x/=10; $x**=10; $x%=4; Output: Add = 15 Sub= 10 Mul = 50 Div = 10

Logical and Relational Operators:

Perl uses logical operators to compare numbers and strings. Most of the time logical operators are used in Conditional Statements. Let us take an example where we can explain all the scenarios. A is greater than B A is less than B A is greater than or equal to B A is less than or equal to B Output: True — equal 5 and 5 True — not equal 6 and 7 True — 7 greater than 6 True — 6 less than 7 True — 6 less than 7 True — 7 greater than 6 You can see examples of logical operators in later sections.

Perl Special Variables

What is Perl Special Variables?

Special variables in Perl are those who have some predefined meaning. These variables denoted with either real Name or Punctuation symbols. We have a special variable for all the Perl supported Variables like scalar special variables, Array special variables, hash special variables. Most of the special variables that we use are of scalars. When we want to use the special variable with its name, then we have to load a Perl module ‘use English,’ to explicitly say Perl interpreter that we are going to use special variables using its Name.

Scalar special variables

Array Special Variables:

Hash Special Variables:

Perl Examples:

Output: llo World He 5–6– a-b-c-d

Perl Regular Expression

What is Regular Expression?

Perl regular expression is strong enough in matching the string patterns within a statements or group of statements. Regular expressions are mostly used in text parsing, pattern matching and much more based on the requirement. We have certain operators, which are specially used by regular expression pattern binding =~ and !~, These are test and assignment operators.

Regular Expression Operators

Perl Match — m// Perl Substitute – s/// Perl Transliterate – tr///

Before going further, We need to know few things about regular expression; there are certain things like Meta characters, wildcards in Perl Regex syntax. The above are the set of characters which can be used during pattern matching. Let’s see few examples. Consider a situation where user provides some input during script execution, and we want to check whether the user entered some name as input or not. We have to write a regular expression syntax to extract your name and print the same. Output: Found Pattern Here, we have written the regular expression as /.(Guru99)./.* match all characters in a string. A ‘.’ in perl regex match refers to any character including space. Let us see how exactly we can construct a Regex. Consider an example of a string of multiple words and digits and special symbols like this “Hello everyone this is my number: +91-99298373639”; Regex : /^\w+\s\w+\s\w+\s\w+\s\w+\s\w+:+\d+-\d+/i Word space word space word space word space word space word space special character : space special character+digits special character –digits.

Perl Match Operators

The match operators are used to match a string within some statement or in a variable. Output: true This small code will print ‘true’, as the perl pattern matching identifies the string in a variable. Basically, Perl searches for the text provided in // throughout the string, even if it finds in one place it will return ‘true’. The pattern can be anywhere in the variable. We can try replacing =~ with !~ to see the difference between those two operators.

Perl Substitution Operator

This operator can be used for searching and replacing any character with either null or some other character. Output: cello how are you Note: We can actually use any pattern matching string as we did earlier in this substitution operator as well. Here we used ‘gi’, g-globally, i-ignore case.

Perl Translation Operator

This is similar to Substitution, but it does not use any perl regular expressions, rather we can directly pass the value or a word which we want to replace. Output: Hello cow are you

Perl File I/O

Perl was designed to manipulate files and I/O operations effectively. Perl main advantage is in file parsing and handling the files. There are many inbuilt functions and operators used during file handling in Perl. Basically, file operations that are performed with Perl are done using FILEHANDLE. We have to define this FILEHANDLE during the opening a file for either read or write. In this Perl script tutorial, you will learn-

Perl Open file

We can open a file using open() function available in Perl. Now we have opened a file, now a question arises. Is it for reading or writing?

Perl Read file & Perl Write file

Perl has certain modes, which need to be used to read, write or append a file. Few examples for reading a file:

Consider we have a perl file with name file.txt and has few lines of text in it. We need to open this file and print the same. or This will print the file content on the output screen. Now, we will write a program to create and write data to a perl file.

This will write the input provided during run-time and creates a file test.txt which will have input. The above way will always try to create a file named test.txt and writes the input into the file; we will write the same to append the file.

Now that we have to see how to read, write and append files using basic examples. We will see few more examples and other functions which help in understanding more about files.

Perl Tell

This method will return the current position of FILEHANDLER in bytes if specified else it will consider the last line as the position.

Perl Seek

Seek function is similar to the fseek system call. This method is used to position the file pointer to a specific location by specifying the bytes followed by either start of the file pointer or end of the file pointer. WHENCE is the position of the file pointer to start. Zero will set it from the beginning of the file. Example:Let input.txt has some data like “Hello this is my world.” Output: this is my world

Unlink is used to delete the file.

Handling Directories:

We can also handle directories through which we can handle multiple files. let’s see how to open a directory. We can use the opendir and readdir methods. or This will print all the available files in that directory.

Perl File Tests & their Meaning

Perl Subroutine

What is Subroutine?

Subroutines are similar to functions in other programming languages. We have already used some built-in functions like print, chomp, chop, etc. We can write our own subroutines in Perl. These subroutines can be written anywhere in the program; it is preferable to place the subroutines either at the beginning or at the end of the code.

Subroutines Example

Now that, we know how to write a subroutine, how do we access it? We need to access or call a subroutine using the subroutine name prefixed with ‘&’ symbol.

Passing Perl Parameters & Perl arguments

Subroutines or perl function are written to place the reusable code in it. Most of the reusable code requires parameters to be passed to the subroutine. Here, we will learn how we can pass arguments to the subroutine. Output: 3 is the value passed @_ is a special array variable which stores the arguments passed to the subroutines.

Perl Shift

We can also use ‘shift’ keyword which shifts one parameter at a time to a variable or $[0],$[1]… which is an individual element of @_ array Output: hello is passed Subroutines are typically used in object-oriented programming and also in places where you may have more reusable code to be placed. Main functionality of subroutines is to do some task and return the result of the reusable code.

We can return a value from subroutine using the return keyword. Output: 11 $result will be holding the value of the $a and $b added. We can also pass hashes and array directly to the subroutine. Output: 1a2b We can also return a hash or an array. Output: Inside Sub-routine2b1aAfter Sub-routine call2b1a

Perl Format

Perl has a mechanism using which we can generate reports. Using this feature, we can make reports exactly the way we want while printing on the Output screen or in a file. A simple format can be written using printf or sprintf functions available in Perl. This will include leading zeros in front of number 30 making a total count of digits to 5. The same can be used for sprintf. Using printf and sprintf, we can obtain most of the Perl formats. In the case of reports, it will be difficult to implement.

=========================================================================== Name Address Age Phone =========================================================================== Krishna Chennai 24 929309242 Shruthi Chennai 24 929309232 The above is a example reports that we need to print in the same manner in Perl. This can be achieved by using the perl printf and perl sprintf. It can effectively be implemented using format. A format can be declared in the below manner. Here, we will be using a particular method write to print the data onto output screen or into the file. Execute the code to see the output. We are using @ symbol to specify the start of the field holder or string, ‘<‘ each character. We are using STDOUT to print on the standard output. We can change this to file handler which we are using to write data into the file. We can replace ‘<‘ to ‘>’ or ‘|’ to change the alignment of the text.STDOUT_TOP is used to design the header of the format.We can also use the same with file handler using FH_TOP( FH is the file handler).This will output the format to the file which we are working on.

Perl Coding Standards

Each programmer will have his own sense of writing the code using certain standards; these standards should be familiar enough that other programmer can understand and support the code properly. Writing code is simple and easy. The problem arises when it needs to be maintained at later stages. Proper guidelines and coding standards need to be followed while writing the code. Perl also defines certain standards that will be useful for programmers to write code. It is advisable to load ‘strict’ and ‘warnings module’ while writing the code. Each of these modules has its own importance. Strict will make us declare the variable before using and also will tell if any bare word present in your code. Warnings module can alternatively be used by passing ‘-w’ option to the Perl interpreter in shebang. Warnings will print on the output screen. Below are few lists of standards.

Use ‘strict’ and ‘warnings’ module. Remove variable, which is not in use. Variable names should be understandable to other users. Ex: $name, @fileData etc. Documentation is required while coding a script. Do not hardcode any values, rather try to fetch those dynamically or ask the user to enter during runtime.(File path, File names). Maximize code reuse. Try to put the reusable code in subroutines. Meaning full names should be given for subroutines. Subroutines need to written with appropriate comments and documentation. Always initialize variables.

Always check the return codes for system calls. Opening a file may or may not happen, having a return code here will display the error status if the file does not exist. Ex: open(FH, <file.txt”) or die(“cannot open the file $!”);

Subroutine should always return a value. Open curly in the same line. Single line BLOCK may be placed in a single line with curly. Use labels during the LOOPS, it would be easy to exit from the loop whenever it is necessary. Use underscore while long phrases of words are written as a variable name or subroutine. Try to use simple regex while coding.

Perfect example with coding standards:

Perl Error Handling

What is an Exception?

An exception is an event that occurs during the program execution which will suspend or terminate your program.

Error Handling

Error Handling is one which every programmer has to take care during programming. Perl also provides error handling techniques with which we can trap the error and handle those accordingly. There are many ways to check for error in the program. We need to examine the return codes of the function that we are using code. If we are able to handle those return codes properly, then most of the error handling can be achieved. What will return in case of system calls? In the case of system calls, the return status will get stored in two special variables $? And $! $! – This will catch the error number or error number associated with the error message. $? – This will hold the return status system() function.

Using Perl operator or Logical

We can use logical or operator for error handling while using system calls. Ex: This will open the file in read mode if the file exists. What if the file is missing?

Perl Eval

Eval function can handle fatal errors, compile time errors, runtime errors and those errors which terminates your code at some point in time. Perl Eval function can have a block of code or an expression. Evals considers everything placed in it as a string. Consider a situation of calling a subroutine which is not defined in the script. In this situation, the script terminates stating “undefined subroutine &XYZ, this error can be handled in the eval function. There are many uses of evals block; one such use is when we want to load the module which is specific to the operating system during runtime. Ex: Divide by zero causes a fatal error; to handle this we can place the code in evals block. Output: syntax error at C:\Users\XYZ\Text.pl line 8, near “) {“ Execution of C:\Users\XYZ\Text.pl aborted due to compilation errors. Example: eval using perl die statement. Output: Caught : Dieing in sub test

Using Perl Try

Perl does not support try, catch and finally code blocks as other programming languages. We can still use them by loading an external Perl module. use Try::Tiny; Using this we can place your code in try block and catch the error in warn block. In place of $@ used in eval Try::Tiny uses $_.

handle errors with a catch handler

Using finally.

Output: foo at C:\Users\XYZ\Text.pl line 4. We can use try, catch and finally in this manner. try { # statement } catch {# statement } finally { # statement }; Or Output: Or Output:

Perl Socket programming

What is a socket?

The socket is a medium through which two computers can interact on a network by using network address and ports. Suppose, A (Server) and B (Client) are two systems, which has to interact with each other using Sockets for running some programs. To implements this we need to create sockets in both A (Server) and B (Client), A will be in the receiving state and B will be in the sending state.

A (Server):

Here, the server wishes to receive a connection from B (Client) and execute some tasks and send the result back to B (Client). When we execute the code, the operating system in A tries to create a socket and binds one port to that socket. Then it will listen from the sender which is B.

B (Client).

Here, the client wishes to send some program from his system to A (Server) for some processing. When we execute the code, the operating system in B tries to create a socket for communicating with A (Server), B has to specify the IP address and the port number of A to which B wishes to connect. If this goes well, both systems will interact to exchange the information through one port. Perl also supports socket programming. Perl has a native API through which sockets can be implemented. To make it easy, there are many CPAN modules using which we write socket programs.

Server operations:

Create Socket Bind socket with address and port Listen to the socket on that port address Accept the client connections which tries to connect using the port and IP of the server Perform operations

Client Operations:

Create Socket Connect to Server using on its port address Perform operations

Socket.io

This is one module for socket programming, which is based on object oriented programming. This module does not support the INET network type used in networks.

IO::Socket::INET:

This module supports INET domain and is built upon IO::Sockets. All the methods available in IO::Sockets are inherited in INET module.

Client and Server using TCP protocol:

TCP is a connection-oriented protocol; we will be using this protocol for socket programming. Before proceeding further let’s see how can we create an object for IO::Socket::INET module and create a socket. The new method in IO::Socket::INET module accepts a hash as an input parameter to the subroutine. This hash is predefined, and we just need to provide the values to the keys which we want to use. There is a list of keys used by this hash.

Server.pl

Client.pl

Note: In socket programming, we will have to execute Server.pl first and then client.pl individually in different command prompts if we are running on local host.

What is Perl Modules and Packages

Modules and Packages are closely related to each other and are independent. Package: A Perl package is also known as namespace and which have all unique variables used like hashes, arrays, scalars, and subroutines. Module: Module is a collection of reusable code, where we write subroutines in it. These modules can be loaded in Perl programs to make use of the subroutines written in those modules.

What are Perl Modules?

Standard modules will get installed during installation of Perl on any system. CPAN: Comprehensive Perl Archive Network – A global repository of Perl modules. Our own customized Perl Modules which can be written by us. Basically, A module when loaded in any script will export all its global variables and subroutines. These subroutines can directly call as if they were declared in the script itself. Perl Modules can be written with .pm extension to the filename Ex : Foo.pm. A module can be written by using ‘package Foo’ at the beginning of the program.

Basic Perl module:

No Output To use this Perl module, we have to place it in currently working directory. We can load a Perl module using require or use anywhere in the code. The major difference between require and use is, require loaded module during runtime and use loads during compile time. Here, in the above example, we are accessing the subroutines using fully qualified module name. We can also access the package using ‘use Arithmetic’.

Exporter:

This module has a default functionality of importing methods. @EXPORT array can be used to pass a list of variables and subroutines which by default will be exported to the caller of the Module. @EXPORT_OK array can be used to pass a list of variables and subroutines which will be exported on demand basis, where the user has to specify while loading the module. By default, add subroutine will be exported. Subtract method won’t be exported if it not specified while loading the module.

Object Oriented Programming in Perl

In this section, we will learn how to create Perl Object oriented Modules. First, let’s see what is the object? An object is an instance using which we can access, modify and locate some data in any Perl module. This is nothing but making your existing Perl package, variables and subroutines to act like class, objects, and methods in reference to other Programming Languages.

Create Class

We already know how to create modules from the previous topic. The purpose of the class is to store methods and variables. A Perl Module will have subroutines which are methods. We need to access those variables and subroutines objects.

Perl Constructor

A constructor in Perl is a method which will execute and return us a reference with the module name tagged to the reference. This is called as blessing the class. We use a particular variable for blessing a perl class, which is bless. The new method used as a constructor for a class, This constructor will create an object for us and will return to the script which is calling this constructor. Here, we need to understand how the object created. Whenever we try to create an object for the class, we need to use the full name of the class. Suppose, if the perl class is located in some lib\Math\Arithmetic.pm. And, if we want to access this perl class from the lib directory then we have to provide the entire path of to the class while calling in the script.

use lib::Math::Arithmetic;

This is how the object creation in Perl happens.

@INC:

How does Perl script know where library module exists? Perl only knows about current directory of the script and the Perl inbuilt library path. Whenever we use, and Perl module, which is not located in the current directory or Perl library Path, the script will always fail. About @INC, this is an array, which holds all directory paths where it has to look for the Perl modules. Try to execute this command and see what will be the output. This will give some output, and that is the path where the lib Modules will be available. Whenever we use any new library module, we need to tell Perl, interpreter, to look into that particular location where Perl module is available. Make this as your first line of code. This will tell your interpreter to look into that Path. or use

Perl Destructor

The destructor of an object is by default called at the end and before your script exits. This is used to destroy your objects from memory.

PERL V/s Shell Scripting








	Programming in  Perl does not cause portability issues, which is common when using different shells in shell scripting.


	Error handling is very easy in Perl


	You can write long and complex programs on Perl easily due to its vastness. This is in contrast with Shell that does not support namespaces, modules, object, inheritance etc.


	Shell has fewer reusable libraries available. Nothing compared to Perl’s CPAN


	Shell is less secure. It’s calls external functions(commands like mv, cp etc depend on the shell being used). On the contrary Perl does useful work while using internal functions.

How PERL is used in Automation Testing

Perl is widely used in automation. It may not be the best programming languages in the world but its best suited for certain types of tasks. Let’s discuss where & why Perl is used for Automation Testing.

Storage Testing

What is Storage? Data stored in Files. Suppose, we have a Storage related Test Case where we have to write data on one partition, read it & verify that the data is written correctly. This can be done manually, but can a manual tester perform the same 10000 times? It will be a nightmare! We need automation Best tool to automate anything related to storage is Perl because of its File Handling Techniques, REGEX and powerful file parsing which consumes least execution time compared to other programming languages. Why we need to test storage? Think about large Data Centers where data will be flowing continuously from one system to other system with 1000’s of records being stored per second. Testing robustness of such storage mechanism is essential. Many companies like HP, Dell, IBM and many server manufacture use Perl as an interface to test functionality in Storage and Networking domains. NetApp is one such company which completely works on Storage and uses Perl as the Programming language to automate the test cases. If you are interested in Perl Automation, then it would be advisable to learn about Storage & Networking Concepts.

Server & Network Testing:

PERL is widely used in server uptime and performance monitoring. Consider a data center which has 100 hosts(servers). You are required to connect to each host, execute some commands remotely. You also want to reboot the system and check when it comes back online. Manually doing this task for all 100 hosts will be a nightmare. But we can easily automate this using PERL Design steps to achieve this above automation using PERL

	Take input from file about the host info like (IP, Username, and Password).


	Use Net::SSH2 to connect to each system and establish a channel to execute the commands.


	Execute set of commands required ex: ls, dir, ifconfig,ps etc.


	Reboot the system.


	Wait for 10minutes for the system to come up.


	Ping the system using Net::Ping module and print the status.

We will code the above scenario. Let’s take a file called Input.txt which will store the complete info about all the hosts in which we need to connect and execute the command. Input.txt 192.168.1.2 root password 192.168.1.3 root password 192.168.1.4 root root123 HostCheck.pl Web Testing Perl is not only restricted to Storage & Network testing. We can also perform Web-based testing using PERL. WWW-Mechanize is one module used for web testing. Basically, it won’t launch any browser to test the functionality of web application’s rather it uses the source code of the html pages. We can also perform browser based testing using Selenium IDE, RC, Web driver. Perl is supported for Selenium.