Perl introductory session notes

May 9, 2010

A simple introduction to perl – Part I

I frequently take sessions on perl for beginners. The notes I commonly use for such a session is placed below. This cannot be claimed to be perfect beginner tutorial, however I hope it will help those who want to take such sessions. I planning to use this for the forthcoming summer session in our Linux Users Group – ILUGC.

Assumptions and limitations

a.It is assumed that perl is already installed in your system

b.It is assumed that you are running Linux

c.Error checking, debugging, best practices are not covered here

d. Anything given under e.g below is to be practised by the student.

Structure of perl program

It is a text file. You can use any text editor to create the program. Normally following line will be the first line

#! /usr/bin/perl

This tells Linux to use /usr/bin/perl executable to interpret rest of the lines in the program.

Commonly .pl extension is used, however you can write without extension also.

Starting with customary hello world program.

Use any editor and create a file with following contents

#! /usr/bin/perl

print “hello world\n”;

Assuming that you have saved it as, we see how to run the program.

Running perl program

Perl programs can be run in two ways. Assuming is your file then

Method a:

$ perl

Method b: Grant executable permission chmod u+x

$ chmod u+x

$ ./

Note: For method b to work #! line is compulsory and ensure that #! occupies first and second character in the file.

If every thing goes well you see hello world in your prompt.

Now that we know how to create and run let us delve into language details.


# symbol is used for comments. All text from # till end of line is treated as comment.


# This is a full line comment

print “hello”; # This is statement+comment

Note: There is no multiline comment.

2. ;

All Statements end with ; like c.


print is simple function to display/output something on monitor/stdout. e.g

print “hello world”;


Variables are typeless i.e there is no datatype like int,char.

Every variable is treated as string and depending on the context will be treated as int, float etc.

There are 4 kinds of variables namely scalars,lists,arrays,hashes.

5 Scalars

Scalar variables contain singular value like 10,hello etc

Name of scalar variable is prefixed with $ symbol.


$name=”ram” # in string context

$age=30; # in numerical context

$age=$age+1; #treated as numeric

$age1=$age.$age; #treated as string

6.Handling quotes

” (double quote) is used when interpolation/substitution is required.



print “hello $name”;

will substitute $name with its value and output ‘hello Raman’.

‘ (single quote) is used when it is a literal string. Special characters

will not be interpreted.



print ‘hello $name’

will print ‘hello $name’.


List variables are noted by symbol (). List is just a list of values – may be constants, scalars etc

e.g (a,b,c) or ($name,$age,$sex)

They can be referred with index also



print “$first\n”;

will output a.

List variables can be assigned like this


8.Conditionals – IF

The syntax of if statement is

if ( condition) {


elsif (condition){


else {


The if statement is similar to c, except

* flowerbrace required even for single statement

* else if is noted by elsif (note missing e).



e.g if ($mark>75){

print “passed with distinction\n”;


elsif ($mark<35){

print “failed\n”;


else {

print “passed\n”;


Alternate form of if statement is

print “a is >10” if ($a>10);

9.Accepting input

Keyboard inputs can be accepted using <STDIN>.


print “enter your name “;


print “Welcome $name\n”;


Accept age.

Type child if age below 12, type senior citizen when age above 60,otherwise type adult



for loop syntax is similar to c. It can be used for iterating on a list. foreach is same as for. Both for and foreach are used interchangeably.

Classical for as in ‘C’ e.g.

for ($i=0;$i<10;$i++){

print “i=$i\n”;


The other way of using for is below.

foreach $i (a,b,c){

print uc $i;



foreach will execute the body once for every element in the list – 3 times in this case. Each time the variable $i will get the value it is iterating ie. $i will be ‘a’ first time ‘b’ second time and ‘c’ the third time. uc – is a perl function to change a string into upper case.

You can combine functions like ‘print uc $i’ instead of print(uc($i))

The output will be ABC


while loop is used to iterate. e.g


while ($i<10){

print “i=$i\n”;



Syntax is similar to C.

11. Default scalar variable $_

$_ is called default variable. It will be used if no other variable is specified. We will see this by an example.


foreach (a,b,c){

print uc ;


The above foreach is similar to what is given under section10, however $i is omitted. Still perl will output same i.e ‘ABC’. This is because perl uses default variable $_ to store and expands the lines as

foreach $_ ( a,b,c){

print uc $_;


Similarly $_ is used in the following case where ‘..’ the generator function is used.

foreach (1..10){

print ;



Arrays are used to store multiple ordered values. Array variables should have prefix @. The size of array need not be specified beforehand. Each element of the array is scalar. Index starts with zero.

e.g @array=(1,2,3);

print @array;

Operations on Array



print @array;

Assigning element


print @array;

New element can be appended at the end using push function


push @array,’4′;

print @array;

Last element can be remove using pop function


$last=pop @array;

print “last=$last\n”;

First element can be removed using shit function



$first=shift @array;

print “first=$first\n”;

An element can be inserted at the beginning using unshift.



unshift @array,’1′;

print “array=@array\n”;

Looping contents of an array using foreach



foreach $i (@array){

print $i;`


$#array is a special variable containing index of last element.It will be -1 for an empty array. In the above example $#array will be 2.

scalar(@array) is function to return the size of array.

Classical for can be used for iterating on array like this



for ($i=0;$i<scalar(@array);$i++){

print “i=$i array element=$array[$i]\n”;


for ($i=0;$i<=$#array;$i++){

print “i=$i array element=$array[$i]\n”;



Hash is associative/named array.It is similar to array, except that we can use strings as index instead of 1..n. Hash variables will have % as prefix. The contents of hash are called values and index is called key.


%fruits= ( ‘apple’ =>’red’,


‘grape’ =>’black’


Other way of populating a hash

e.g %fruits =(‘apple’,’red’,’banana’,’yellow’,’grape’,’black’);

Here the list should contain even number of values. First element will be treated as key, second element value, third element key, fourth value and so and so forth. In short odd elements will be keys, even elements will be values.

Individual elements accesed by means of $hash{key}

e.g. print “colour of appple is $fruits{apple}”;

Adding new element



Note the { } instead of [ ] as in the case of array;

Looping on hashes – keys function


foreach $f (keys %fruits){

print “Color of $f is $fruits{$f}\n”;


Explanation: keys is a function which return a list of key values.The list ( ) will contain apple,banana,grape while running.

14. Subroutines

Subroutines can be defined using sub keyword. The arguments passed will be in a default array @_;




sub add {


print $a+$b;


This should give output 30.

You can return value using return statement.

15. Scope of variables

By default all variables are global i.e available throughout the file. You can limit scope to a block/sub by using my.


$v1=10; $v2=30; #v1,v2 global



sub add{

my ($i,$j)=@_;

print “inside add sub value of i=$i j=$j\n”;

print “inside add sub value of globals v1=$v1 v2=$v2 v3=$v3\n”;

return $i+$j;


print ” Value of globals v1=$v1 v2=$v3\n”;

print ” Value of scoped variables v3=$v3\n”;

print ” Value of variables inside sub i=$i j=$j\n”;

You can limit scope to a block also


for (my $i=0;$i<10;$i++){

print “inside for i=$i\n”;


print “outside for i=$i\n”;

16.use strict

In perl you need not define variables before using. By default all variables are global. However, this may lead to errors due scope conflict or errors in naming. ‘use strict’ is a pragma which will help in avoiding it. Once use strict is used, every variable has to be declared with proper scope using my or our.


use strict;



sub add {


print $a+$b;


The above code will not run and produce error. The corrected one will be like this


use strict;

my $v1=10;

my $v2=20;


sub add {

my ($a,$b)=@_;

print $a+$b;


17. References

References are address of the variable, similar to pointers in c. You can take a reference by using \. It can be dereferenced by using $$;




print “value of a= $$ref_toa”;

18.file handling

File handling can be done after opening a file and getting handle similar to C.

e.g open($fh,”r”,”data.txt”);

here $fh – file handle

r – open read only

data.txt – name of the file. Full path name can also be given

File reading can be done like


File writing

print $fh “hello”;

Example. Open data.txt file. Copy contents to udata.txt duly converted into upper case


open ($fh,”r”,”data.txt”); #open file read only

open ($fh1,”w”,”udata.txt”; #Open file write mode

while ($line=<$fh>){ #read line by

print “line=$line”; #display content on screen

print $fh1 uc($line); #write upper cased content




The session will be closed by showing few small (less than 10 line script)

1.A network socket

2.A Desktop program using Tk

3.A database interface using dbi

4.A web page using cgi.