Complete Perl Tutorial

Warning : This chapter is only for those who knows other programming language like php, python, c, c++ etc., If you are new to programming language starts with chapter 2.

In this chapter, I will take you complete perl language in 1 chapter. Detail of tutorial are listed beside, but Let's get you all basic down in first chapter.

What is Perl and Why to Learn Perl ?

  1. Perl is a high-level programming language.
  2. it has easy to understand syntax like PHP, Python.
  3. Perl is also cross-platform independence and pretty easy to maintain.
  4. It's a top pick for CGI-Scripts, Sysadmins and even Database Manipulation.

How to start ?

Perl is interpreted language that means no compiling our code like C. Perl use an interpreter which after installing should be available at /usr/bin/perl or /usr/bin/local/perl in unix like machine and for windows , it should be available at place where you have either installed or most applications are installed by default.

#!/usr/bin/perl

If you're on Linux or OS X, you'll already have some version of Perl but if you're on Windows then you'll be given a choice between ActiveState and StrawBerry.

ActiveState: Modules fetched using the Perl Package Manager, which has nearly everything you could want except for very new modules. Associated with Windows.

StrawBerry: Up to date modules and automatic updates from CPAN. Comes with MinGW (Contains gcc, make, ld and other hander tools). Associated with Unix (Due to the environment).

You'll also need a text editor, this part is all about preference.
People who want something simple should look out for NotePad++ or Gedit whereas Vim and Emacs seek for optimum customisation.

Your first program, Hello World

To output text to the Standard Output Stream ( Known as STDOUT ), we will use print. This function will be used by us to display our string. 

#!/usr/bin/perl

use strict;
use warnings;

print "Hello World!\n";

Perl will not give us a newline by default using print, that is why,  we use the semi-colon to mark the end of our statement and \n for adding new line.

Print does not limit us to one Standard Stream, we can output our text to the Standard Error Stream (STDERR)

#!/usr/bin/perl

print STDERR "Hello World!\n";

Utilising use strict is advised strongly ,The strict pragma disables certain Perl expressions that could behave unexpectedly or are difficult to debug, turning them into errors. The effect of this pragma is limited to the current file or scope block.  and use warnings will feed you any typos made along the way. There are utilized as follows

#!/usr/bin/perl
use strict;
use warnings;

Variables, Arrays and Hashes

In programming, we use variables mainly to store information and values.

  1. In perl, we use the Scalar - $ symbol to define a variable.
  2. The symbol goes before the name we have assigned the variable.
  3. It is a good idea to use the word my in front of our variable for good practise, as this localizes the variable so it becomes local to the file/block/eval (Meaning if we have a variable with the word my before it within a loop, and we try to access it from outside the loop, it won't work).

Look at  an example below.

#!/usr/bin/perl

use strict;
use warnings;

for ($i=0;$i<10;++$i){
    my $var = "Hello Tom\n";
    print "$var";
}

A my declares the listed variables to be local (lexically) to the enclosing block, file, or eval. If more than one variable is listed, the list must be placed in parentheses.

Arrays are effectively a list of scalars which basically means strings and also numbers .

We can identify arrays with the @ symbol before the name of our array. We then assign it values in a similar manner to a variable. Here is an example below.

#!/usr/bin/perl

use strict;
use warnings;

my @array = ("Tom", 15, "America");

print "My name is $array[0], I'm $array[1] years old and I live in $array[2]";
Here are things you must remember.

To access items individually from an array, we can use our variable symbol in combination with their place in the array being called, starting from the number 0 as shown above.

An array known as ARGV will be used to access data that was input via the command line. Here is a quick example.

#!/usr/bin/perl

use strict;
use warnings;

if ($#ARGV < 10){
    print "There are less than ten arguments";
} else {
    print "There are more than 10 arguments";
}

Let me break this down for you :-

if loop will check to see if there are less than 10 command line arguments ($#ARGV < 10) and if there are less, it will print our first string, but if there are more it will trigger else and print the second string.

Another useful function relating to Arrays is push(@arrayname, "StringAddedToEnd") and pop(@arrayname) which allow you to add items to the end of an array and with pop; take them away from the end.

Hashes are a way of assigning a certain key a value. They are then called with $hash{key}. Here is an example of assigning 3 keys a value then printing them.

#!/usr/bin/perl

use strict;
use warnings;

my %family = (
'Dad' => "James",
'Mom' => "Mary",
'Sister' => "Sarah",
);

print "My father's name is $family{Dad}, my mothers name is $family{Mom} and my sisters name is $family{Sister}.";

Mathematical Operations

  1. Addition => $a = $b + $c;
  2. Subtraction => $a = $b - $c;
  3. Multiplication => $a = $b * $c;
  4. Division => $a = $b / $c;
  5. Exponent => $a = $b ** $c;
  6. Modulo => $a = $b % $c;
  7. Increment then return => ++$a;
  8. Return then increment => $a++;
  9. Decrement then return => --$a;
  10. Return then decrement => $a--;
  11. Add $b to $a => $a += $b;
  12. Subtract $b from $a => $a -= $b;
  13. Append $b to $a => $a .= $b;

String

  1. Concatenation => $a . $b;
  2. $a repeated $b times => $a x $b;

Loops

Loops are functions which will iterate an action until a set condition is met. I will be going over 3 types of loops. For, while and until.

For

Syntax : 

for ( InitializedVar; Condition; VarModifier ){

}

A common variable modifier (3rd expression in the for loop above), is the incrementing numerical operator. Here is an example below which will print the numbers 1 to 100.

#!/usr/bin/perl

use strict;
use warnings;

for (my $i=0;$i<=100;$i++) {
    print "$i\n";
}

It is saying that $i is set to zero and while it is less than or equal to 100, increment it. We are then printing $i as it is incremented.

While

You can do this multiple ways, having a loop that executes a statement first before checking or one that will evaluate our expression. Here is one that evaluates an expression first.

#!/usr/bin/perl

use strict;
use warnings;

my $i = 0;

while ($i <= 100) {
    print "$i\n";
    $i++;
}

Do while loop -  perform the statement pre-evaluation. 

#!/usr/bin/perl

use strict;
use warnings;

my $i = 0;

do {
    print "$i\n";
    $i++;
} while $i <= 100;

Until

This is quite opposing of the while loop as it performs the loop until the expression is false, and when it becomes true, it finishes. You have multiple options as to what gets executed first as seen in the while example, so I will provide two examples. Here is one where the expression is tested first.

#!/usr/bin/perl

use strict;
use warnings;

my $i = 0;

until ($i > 100) {
    print "$i\n";
    $i ++;
}

And here is an until loop which will perform the statement before being evaluated.

#!/usr/bin/perl

use strict;
use warnings;

my $i = 0;

do {
    print "$i\n";
    $i++;
} until $i > 100;

Subroutines

Subroutines are user-defined functions. They have certain properties to them, as follows:

  1. They can be put anywhere in the main program.
  2. Any passed-in arguments go to an array called @_.
  3. The subroutine can be called with the ampersand (&) symbol in front of it.
  4. The return statement is utilized to exit the subroutine

Example of a subroutine utilising individual variables.

#!/usr/bin/perl

use strict;
use warnings;

sub operatorz {

    my $addition = $_[0] + $_[1];
    my $subtraction = $_[0] - $_[1];
    my $multiplication = $_[0] * $_[1];
    print "$_[0] + $_[1] = $addition\n$_[0] - $_[1] = $subtraction\n$_[0] * $_[1] = $multiplication\n";

}

&operatorz(5,5);

The explanation of what is happening is very simple.

  1. We have created our subroutine known as operatorz.
  2. Within this, there are several numerical operators and finally a print function.
  3. Outside of the subroutine, we are calling the subroutine with our arguments (5,5) which are passed to the subroutine.
  4. As explained beforehand, because they were passed to a sub-routine, they show in in the @_ array as @_ = (5,5); and are thus individually accessed via $_[0] for the first 5 and $_[1] for the second 5.

Modules

Modules are a set of functions exclusive to lib, which very important to us in order to make life simpler in finding what we need.

We invoke a module via the use [ModuleName] syntax, exactly the same way we use the strict module. This will go in the line after our interpreter location. You are also not restricted to using one module per perl script, so don't worry!

Here is an example of a perl script utilizing modules.

#!/usr/bin/perl

use LWP::Simple;
use LWP::UserAgent;

use strict;
use warnings;

my $site = "http://www.youtube.com/";
my $ua = LWP::UserAgent->new() or die "No UA for you!";
my $req = $ua->get($site);

if ($req->is_success) {
    print "Successfully accessed website\n";
    exit 0;
} else {
    die "Unsuccessful :(\n";
}

Here's a quick explanation of what's going on.

  1. As you can see we are using the LWP modules as an API to visit youtube.
  2. LWP::UserAgent allows us to initialize a new user agent.
  3. We then use $ua->get to fetch our site.
  4. Our conditional operator if is checking to see if our modest request was successful and outputs a congratulatory string, then exits successfuly with exit 0.
  5. If in the case the operation was a failure, else will trigger and our program will print a sad string to STDERR using the die function.

Loading ...

Related Results :

  1. Full Tutorial
  2. Complete Perl Tutorial
Note :
  • Related Posts are generally User Blog posts.
  • or Other tutorials from other networks of w3clan.com.
  • Any registered user can create related posts based on search term tags.

About the Author