Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 13

PERL LEARNING MATERIAL I

Overview of Perl
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.

1. What is Perl?

Perl stands for "Practical Extraction and Reporting Language" even though there is no
authorized acronym for Perl.

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 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. Its 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
flavour of Linux distribution being used, making it less and less portable

 Small specific tasks in Perl become very easy and quick.

Perl Installation

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

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 –
$perl -e 'print "Hello World\n"'
This execution will produce the following result –
Hello, world

Script Mode Programming


Perl Example: HelloWorld.pl
#!/usr/bin/perl -w
#this is just a comment…
print "Hello World";
Let’s take a look at it by line:
#!/usr/bin/perl
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.
print "Hello World";
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 HelloWorld.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:
C:\> perl path\ HelloWorld.pl
or, if perl.exe is not in your path:
C:\> c:\perl\bin\perl.exe HelloWorld.pl
On Linux/Unix
You just have to open the Terminal and write:
perl HelloWorld.pl
If you can't run the program, make sure you have eligibility to run it. Type in the Terminal:
chmod +x HelloWorld.pl
Your program is now executable and ready to run. To execute, write:
HelloWorld.pl

This execution will produce the following result −


Hello world

2. The Input Operator

Perl makes input and output extremely easy.

Perl - <stdin>

<STDIN> stands for standard input. It can be abbreviated by using simple <>. By declaring a
scalar variable and setting it equal to <STDIN> we set the variable equal to whatever will be
typed by our user at the command prompt.

GetAge.pl:
#!usr/bin/perl
print "How old are you?";
$age = <>;
print "WOW! You are $age years old!";

Output:
$ perl GetAge.pl
How old are you?66
WOW! You are 66

Circle.pl:
#!usr/bin/perl
print "What is the radius of the circle?";
chomp ($r = <>);
$diameter = (2 * $r);
$area = (3.14 * ($r ** 2));
$cir = ($diameter * 3.14);
print "Radius: $r\n Diameter: $diameter\n Circumference: $cir\n Area: $area";

Output:
$ perl Circle.pl
What is the radius of the circle?5
Radius: 5
Diameter: 10
Circumference: 31.4
Area: 78.5

3. Print and Printf

We will start this chapter by taking a variable and giving it some value. Let's see how it is
done.
$a = 10;

In Perl, scalar variables (having single value) are written after dollar sign ($). So, 'a' written
after dollar sign in the above example is a variable.

$a = 10; - We have taken a variable 'a' and assigned it a value of 10.

Variables in Perl can have any number of letters, digits and underscores (_) but the first
letter of a variable must be a letter or underscore and not a digit.

Now, let's print the value of a variable.

$a = 10;
print "$a\n";

Output
10
You can see that the value of 'a' got printed in the previous example in place of $a and it is
this easy to print the value of a scalar variable. To print the value of a scalar variable, we
have to just write the variable after the dollar sign ($) and that's it.
Let's see one more example:

$a = 10;
$b = 20;
$c = $a+$b;
print "$c\n";
print "$a+$b\n";
Output
30
10+20

You can see that in place of "$a+$b", "10+20" got printed. This means that the values of 'a'
and 'b' got printed and the expression ( $a+$b i.e., 10+20 ) was not evaluated. We can also
evaluate an expression inside the print statement. Let's see an example explaining this.

$a = 10;
$b = 20;
print "Product of $a and $b is ",$a*$b," and their difference is ",$b-$a,".\n";

Output
Product of 10 and 20 is 200 and their difference is 10.
$a = 10; - It means that we are taking a variable 'x' and giving it a value 10.
$b = 20; - Similarly, we are giving a value of 20 to 'y'.
print "Product of $a and $b is ",$a*$b," and their difference is ",$b-$a,".\n";

Let's learn about this line of code.


Expressions written in (" ") are printed as they are and are not evaluated (only variables
written after $ are replaced with their values.). So, 'Product of' is printed and then the value
of 'a' is printed (i.e. 10), then 'and' is printed as it is. Then the value of b (i.e. 20) and then
$a*$b is calculated and printed. (i.e. 200).
Let's see one more example:
$a = 10;
$b = 20.23;
$c = "Hey";
$d = "5";
print "$a\n$b\n$c\n$d\n";

Output
10
20
Hey
Here, 'a' is an integer, 'b' is a floating point (decimal number) and 'c' is a string.
String is a collection of characters. In simple English, it is a letter, word, sentence or
collection of sentences. You will go through a whole topic on string. So, leave it for that time
if you are getting confused and just keep in mind that strings are characters, words or
sentences and these are written between ' ' or " ". Since 'Hey' and '5' are written between "
" i.e. "Hey" and "5", so they are strings.
Using here documents for multi-line printing

A here-document can also be used to create a string with multiple lines and preserve
whitespaces and newlines. Its syntax is:

$str = <<"END";
String
with
multiple lines
END

Everything written before END will be part of the string "str" (with whitespaces and
newlines preserved). Let's see an example on this:

$str = <<"END_MAIL";
Hey there,

I am just creating this mail to learn here-docs.

Thanks for your time.

XYZ
END_MAIL
print "$str";

Output
Hey there,

I am just creating this mail to learn here-docs.

Thanks for your time.

XYZ

You can see that everything written before END_MAIL becomes a part of string 'str' with
preserved newlines.

We can concatenate or join two strings by using . operator. Let's see its example.

$a = "Codes";
$b = "Dope";
$cat = $a.$b;
print ($cat,"\n");

Output
CodesDope
You can see that the (.) operator joined two strings ("Codes" and "Dope") to form a new
string, "CodesDope".
print ("5"+"2","\n");
print (5 . 2,"\n");

Output
7
52

When we used (+) on two strings ( "5" and "2" ), they got converted to integer and we got 7
as the result and when (.) on integers ( 5 and 2 ), they got converted to strings and we got
52 ( after joining both ) as the result. And this is what I was trying to say that in Perl, strings
and numbers are converted into each other according to the requirement.

int() function

int() function takes a number and rounds it down to the nearest integer. It means that
int(10.97) will give 10. Let's see an example for the same.

$a = 10.97;
$value = int(10.97);
print “$value”;

Output
10

Escape Sequences

We know that \n designates a newline character and it is one of the escape sequences.
There are many others in Perl. Here are the most important ones:
 \\ - backslash (to print \ on screen)
 \$ - dollar sign (to print $ on screen)
 \r - return sign
 \@ - at-sign (to print @ on screen)
 \n - a newline character
 \" - double-quote character (")
 \t - a tab character (prints a tab space)

Let's see an example to see them working.

print "Hey, \"How are you\".


I am just asking but I can give you \$100 for your answer
\tYes, you can contact me \@ xyz.com for money.\n"

Output
Hey, "How are you".
I am just asking but I can give you $100 for your answer Yes, you can contact me @
xyz.com for money.

You know how to print something on the screen. In the next chapter, you will learn to take
input from the keyboard.

Swapping

Swapping means interchanging the values of two variables. eg - if x is 10 and y is 5, then


after swapping x will be 5 and y will be 10.
So, let's see how it is done.

$x = 10;
$y = 5;
($x, $y) = ($y, $x);
print "x is $x\n";
print "y is $y\n";

Output
x is 5
y is 10

And it's done.


Don't forget to put the variables which you want to swap in brackets.

sprintf and printf

sprintf is used to print in a formatted way. Suppose you have a variable having a value of
3.14159, then by using sprintf function you can control the precision of digits after decimal
while printing. It means that you can print only 3.14.
There are specific characters which start with % (percentage sign) which are converted into
specific type. For example, %s converts into a string, %i into an integer, etc. Let's first see an
example:

print sprintf ("My name is %d and I am %s years old","Sam",19);


Output:
My name is Sam and I am 19 years old

You can see that string got printed in place of '%s' and an integer got printed in place of '%i'.
Let's see the table of supported conversions in Perl with examples.
Conversion
Function Example
sign
%s String "%s","Sam" -> Sam

%d or %i Integer "%i",10 -> 10


"%i",10.1 -> 10

%f Float "%f",10.1 -> 10.100000


Floating point number in scientific "%e",10.1 ->
%e
notation 1.010000e+01
%c Character from ASCII number "%c",97 -> a
%b An integer in binary "%b",10 -> 1010
%% Actual percent sign "%%" -> %
%o An integer in octal "%o",10 -> 12
An integer in hexadecimal (%X for
%x and %X "%x",10 -> a
uppercase)

We can specify the space used by a string on the screen by writing a number between %s.
For example, "%5s","Hey" prints " Hey" and "%-5s","Hey" prints "HEY ".
We can also use a number between %f for precise printing of decimal number. For example,
""%.2f",3.14159" prints "3.14" Let's see an example:

printf ("%5s\n","Hey");
printf ("%-5s\n","Hey");
printf ("%.2f\n",3.14159);

Output
Hey
Hey
3.14

******************************@@@@@@@@@@**************************

Prepared by Madhan Kumar


Mail: madhan.kumarr7@gmail.com
Contact: +91 7502682207

*******************************@@@@@@@@@@**************************

You might also like