Perl introductory session notes

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 prog.pl, we see how to run the program.

Running perl program

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

Method a:

$ perl prog.pl

Method b: Grant executable permission chmod u+x prog.pl

$ chmod u+x prog.pl

$ ./prog.pl

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.

1.Comments:

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

e.g

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

3.print

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

print “hello world”;

4.Variables

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.

eg.

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

e.g

$name=”Raman”;

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.

e.g

$name=’Raman’;

print ‘hello $name’

will print ‘hello $name’.

7.Lists

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

e.g

$first=(a,b,c)[0];

print “$first\n”;

will output a.

List variables can be assigned like this

($name,$age)=(‘Raman’,20);

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

$mark=40;

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

e.g

print “enter your name “;

$name=<STDIN>;

print “Welcome $name\n”;

Exercise:

Accept age.

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

10.Loops

for

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;

}

Explanation:

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

while loop is used to iterate. e.g

$i=0;

while ($i<10){

print “i=$i\n”;

$i++;

}

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.

e.g

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 ;

}

12.Arrays

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

Assignment

@array=(1,2,3);

print @array;

Assigning element

$array[3]=4;

print @array;

New element can be appended at the end using push function

e.g.

push @array,’4′;

print @array;

Last element can be remove using pop function

e.g.

$last=pop @array;

print “last=$last\n”;

First element can be removed using shit function

e.g

@array=(1,2,3);

$first=shift @array;

print “first=$first\n”;

An element can be inserted at the beginning using unshift.

e.g

@array=(1,2,3);

unshift @array,’1′;

print “array=@array\n”;

Looping contents of an array using foreach

e.g

@array=(1,2,3);

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

e.g

@array=(1,2,3);

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”;

}

13.Hashes

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.

e.g

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

‘banana’=>’yellow’,

‘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

e.g.

$fruits{‘orange’}=’orange’;

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

Looping on hashes – keys function

e.g

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 @_;

e.g

$v1=10;$v2=20;

add($v1,$v2);

sub add {

($a,$b)=@_;

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.

e.g

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

$v3=30;

$v3=add($v1,$v2);

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

e.g

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.

e.g

use strict;

$v1=10;$v2=20;

add($v1,$v2);

sub add {

($a,$b)=@_;

print $a+$b;

}

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

e.g

use strict;

my $v1=10;

my $v2=20;

add($v1,$v2);

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 $$;

e.g

$a=10;

$ref_toa=\$a;

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

$line=<$fh>;

File writing

print $fh “hello”;

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

e.g

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

}

close($fh);

close($fh1);

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.

6 Responses to Perl introductory session notes

  1. C.Raja says:

    I like your blog article very much.

    It’s very nice guide for the perl beginners.

    In example code 17 for reference variables, there is an typing error.

    $ref_toa=\$a;

    print “value of a= $$ref”;

    To correct the error, the variable deceleration are print statement variable name must be changed.

  2. uday says:

    Hi,

    See that yout session id based on 5.10? Shouldn’t it be based on 6?

    Due to the steep learning curve with 5.10, people would be better off with python. Python doesn’t involve learning curve, though you will have night-mares with indentation.

    • ramanchennai says:

      I do not understand ‘session id based on 5.10? Shouldn’t it be based on 6’. I presume you are talking about Perl 6. Well, I teach what is currently stable.

      About Python trumpeting, I feel the world has space for more than one language and mono-culture is bad.

      • uday says:

        Yeah you got it correct, i meant Perl 6. Felt it was obvious. BTW, the current stable version is 5.12; please update yourself.

        ‘Python trumpeting’? I have used Perl for nearly 8 years! And Python for 6 months. Please stop taking the very mention of an alternative as mono-culture.

      • ramanchennai says:

        The sessions are not about specifc version. It is very basic tutorial thats all. I don’t even compare with other scripting languages. There is no need to talk about python, learning curve etc in a very basic tutorial about perl, any such talk is trumpeting – all the more when the article doesn’ t talk about other scripting languages. Please stop mentioning python at the very mention of perl.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: