Saturday, March 12, 2016

Perl Tutorial

Saturday, March 12, 2016 Posted by Sandeep Kumar Jha

Perl is a general-purpose programming language originally developed for text manipulation and now used for a wide range of tasks including system administration,
web development, network programming, GUI development, and more.

First Perl Program

Interactive Mode Programming

You can use Perl interpreter with -e option at command line, which lets you execute Perl statements from the command line. Let's try something at $ prompt as follows


Comments in Perl

Comments in any programming language are friends of developers. Comments can be used to make program user friendly and they are simply skipped by the interpreter without impacting the code functionality. For example, in the above program, a line starting with hash #is a comment.


Whitespaces in Perl

A Perl program does not care about whitespaces. Following program works perfectly fine


Single and Double Quotes in Perl

You can use double quotes or single quotes around literal strings as follows


Escaping Characters


Perl uses the backslash (\) character to escape any type of character that might interfere with our code. Let's take one example where we want to print double quote and $ sign


Data Types

Perl is a loosely typed language and there is no need to specify a type for your data while using in your program. The Perl interpreter will choose the type based on the context of the data itself.

Perl has three basic data types scalars, arrays of scalars, and hashes of scalars, also known as associative arrays. Here is a little detail about these data types.


S.N.
Types and Description
1
Scalar
Scalars are simple variables. They are preceded by a dollar sign ($). A scalar is either a number, a string, or a reference. A reference is actually an address of a variable, which we will see in the upcoming chapters.
2
Arrays
Arrays are ordered lists of scalars that you access with a numeric index which starts with 0. They are preceded by an "at" sign (@).
3
Hashes
Hashes are unordered sets of key/value pairs that you access using the keys as subscripts. They are preceded by a percent sign (%).

Example



Variables

Variables are the reserved memory locations to store values. This means that when you create a variable you reserve some space in memory.

Based on the data type of a variable, the interpreter allocates memory and decides what can be stored in the reserved memory. Therefore, by assigning different data types to variables, you can store integers, decimals, or strings in these variables.

Creating Variables

Perl variables do not have to be explicitly declared to reserve memory space. The declaration happens automatically when you assign a value to a variable. The equal sign (=) is used to assign values to variables.

Keep a note that this is mandatory to declare a variable before we use it if we use use strict statement in our program.
The operand to the left of the = operator is the name of the variable, and the operand to the right of the = operator is the value stored in the variable. For example

$age = 25;             # An integer assignment
$name = "John Paul";   # A string
$salary = 1445.50;     # A floating point

Scalar Variables

A scalar is a single unit of data. That data might be an integer number, floating point, a character, a string, a paragraph, or an entire web page. Simply saying it could be anything, but only a single thing.

Here is a simple example of using scalar variables

Example


Array Variables

An array is a variable that stores an ordered list of scalar values. Array variables are preceded by an "at" (@) sign. To refer to a single element of an array, you will use the dollar sign ($) with the variable name followed by the index of the element in square brackets.

Here is a simple example of using array variables

Example


Hash Variables

A hash is a set of key/value pairs. Hash variables are preceded by a percent (%) sign. To refer to a single element of a hash, you will use the hash variable name followed by the "key" associated with the value in curly brackets.

Here is a simple example of using hash variables

Example


Array

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.

Here is a simple example of using the array variables

Example


Array Creation

Array variables are prefixed with the @ sign and are populated using either parentheses or the qw operator. For example

@array = (1, 2, 'Hello');

@array = qw/This is an array/;

Array Size

The size of an array can be determined using the scalar context on the array - the returned value will be the number of elements in the array

@array = (1,2,3);
print "Size: ",scalar @array,"\n";

Example


Perl Conditional Statements

Perl programming language provides the following types of conditional statements.

Statement
Description
An if statement consists of a boolean expression followed by one or more statements.
An if statement can be followed by an optional else statement.
An if statement can be followed by an optional elsif statement and then by an optional else statement.
An unless statement consists of a boolean expression followed by one or more statements.
An unless statement can be followed by an optionalelse statement.
An unless statement can be followed by an optionalelsif statement and then by an optional else statement.
With the latest versions of Perl, you can make use of the switch statement. which allows a simple way of comparing a variable value against various conditions.

Perl IF Statement

Syntax

The syntax of an if statement in Perl programming language is

if(boolean_expression){
   # statement(s) will execute if the given condition is true
}

Example


Perl IF...ELSE statement

Syntax

The syntax of an if...else statement in Perl programming language is

if(boolean_expression){
   # statement(s) will execute if the given condition is true
}else{
   # statement(s) will execute if the given condition is false
}

Example



Perl IF...ELSIF statement

Syntax

The syntax of an if...elsif...else statement in Perl programming language is

if(boolean_expression 1){
   # Executes when the boolean expression 1 is true
}
elsif( boolean_expression 2){
   # Executes when the boolean expression 2 is true
}
elsif( boolean_expression 3){
   # Executes when the boolean expression 3 is true
}
else{
   # Executes when the none of the above condition is true
}

Example


Switch statement 

Syntax

The synopsis for a switch statement in Perl programming language is as follows

use Switch;

switch(argument){
   case 1            { print "number 1" }
   case "a"          { print "string a" }
   case [1..10,42]   { print "number in list" }
   case (\@array)    { print "number in list" }
   case /\w+/        { print "pattern" }
   case qr/\w+/      { print "pattern" }
   case (\%hash)     { print "entry in hash" }
   case (\&sub)      { print "arg to subroutine" }
   else              { print "previous case not true" }
}

Perl - Loops


Perl programming language provides the following types of loop to handle the looping requirements.

Loop Type
Description
Repeats a statement or group of statements while a given condition is true. It tests the condition before executing the loop body.
Repeats a statement or group of statements until a given condition becomes true. It tests the condition before executing the loop body.
Executes a sequence of statements multiple times and abbreviates the code that manages the loop variable.
The foreach loop iterates over a normal list value and sets the variable VAR to be each element of the list in turn.
Like a while statement, except that it tests the condition at the end of the loop body
You can use one or more loop inside any another while, for or do..while loop.

Perl while Loop

Syntax

The syntax of a while loop in Perl programming language is

while(condition)
{
   statement(s);
}

Example


Perl for Loop

Syntax

The syntax of a for loop in Perl programming language is

for ( init; condition; increment ){
   statement(s);
}

Example


Perl foreach Loop

Syntax

The syntax of a foreach loop in Perl programming language is

foreach var (list) {
...
}

Example


Perl do...while Loop

Syntax

The syntax of a do...while loop in Perl is

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

Example


Perl nested Loop

Syntax

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

for ( init; condition; increment ){
   for ( init; condition; increment ){
      statement(s);
   }
   statement(s);
}

Example


Perl string manipulations

String concatenation

To concatenate two strings together, just use the . dot:

$a . $b;
$c = $a . $b;
$a = $a . $b;
$a .= $b;

Example


Substring extraction

The counterpart of string concatenation is substring extraction. To extract the substring at certain location inside a string, use the substr function:

$second_char = substr($a, 1, 1);
$last_char = substr($a, -1, 1);
$last_three_char = substr($a, -3);

Example


Substring search

In order to provide the second argument to substr, usually you need to locate the substring to be extracted or replaced first. The index function does the job:

$loc1 = index($string, "abc");
$loc2 = index($string, "abc", $loc+1);

print "not found" if $loc2<0;

sqrt Function

This function returns the square root of EXPR, or $_ if omitted. Most of the time, this function returns a floating point number.

Syntax

Following is the simple syntax for this function −

sqrt EXPR

sqrt

Example



The join function

Although not actually a pattern matching function, the counterpart of the split function is the join function, which connects all members in an array with some fixed strings:
my $string = join " ", @words; # this time the " " is just what it is, one space character

Example


sprintf Function

Syntax

Following is the simple syntax for this function −

sprintf FORMAT, LIST

Example

Following is the example code showing its basic usage −



Menu Parser Example