Sunday 9 November 2014

A Beginners Perl Guide



What is Perl and Why Would I Learn it?

Perl is a high-level programming language and thus has an easy to understand syntax when compared to a language such as Assembly which is Low-level. It also means it can have cross-platform independence and easier to maintain. It's a top pick for CGI-Scripts, Sysadmins and even Database Manipulation.

What do I need to start!

Perl is interpreted so instead of compiling our code like C, we use an interpreter which after installing should be either at /usr/bin/perl or /usr/bin/local/perl (Tip: If you're on a *nix system you can try the where perl command to find the interpreter). It's important to make note of this as we will be directing the computer to our interpreter, and thus in my case, scripts will start with

===========================================================
Code:

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

Last and final thing is to remember to enjoy yourself while programming with Perl, let it be a hobby and don't get stressed out if you don't understand something. There are plenty of knowledgeable people within and especially outside of this forum, places include PerlMonks.org or PerlGuru.com.

This tutorial will briefly cover
Hello World
Variables, Arrays and Hashes
Operations
Loops
Subroutines
Modules
Resources and Practise Sites



Your first program, Hello World

This is most likely everyone's first program starting off.

Firstly, remember to tell our computer where the interpreter is! (Note: the # symbol by itself is also used for commenting).

===========================================================
Code:

#!/usr/bin/perl

===========================================================
Now 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. This may remind people of how we output a string in Python 2.

===========================================================
Code:

#!/usr/bin/perl
print "Hello World!\n";

===========================================================

But wait, why is there a newline character and a semi-colon there? The answer is that Perl will not give us a newline by default using print, we use the semi-colon to mark the end of our statement. Print does not limit us to one Standard Stream, we can output our text to the Standard Error Stream (STDERR)

===========================================================
Code:

#!/usr/bin/perl
print STDERR "Hello World!\n";

===========================================================

Protip - Utilising use strict is advised strongly so you get into good practise (Aka moan about you for more or less any small thing, but you'll thank it later!) and use warningswill feed you any typos made along the way. There are utilized as follows

===========================================================
Code:

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

===========================================================

Variables, Arrays and Hashes


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

In perl, we use the Scalar - $ symbol to define a variable. The symbol goes before the name we have assigned the variable. 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). I've provided an example below.

Working Code

===========================================================

Code:

#!/usr/bin/perl

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

===========================================================

Broken Code

===========================================================
Code:

#!/usr/bin/perl

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

print "$var";
===========================================================

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.

===========================================================
Code:

#!/usr/bin/perl
use strict;

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.

===========================================================
Code:

#!/usr/bin/perl
use strict;

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, our 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") andpop(@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.

===========================================================
Code:

#!/usr/bin/perl
use strict;

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}.";
===========================================================

Operations

Mathematical
Addition => $a = $b + $c;
Subtraction => $a = $b - $c;
Multiplication => $a = $b * $c;
Division => $a = $b / $c;
Exponent => $a = $b ** $c;
Modulo => $a = $b % $c;
Increment then return => ++$a;
Return then increment => $a++;
Decrement then return => --$a;
Return then decrement => $a--;
Add $b to $a => $a += $b;
Subtract $b from $a => $a -= $b;
Append $b to $a => $a .= $b;

String

Concatenation => $a . $b;
$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
Our syntax goes as follows 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.

===========================================================
Code:

#!/usr/bin/perl
use strict;

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.

===========================================================
Code:

#!/usr/bin/perl
use strict;

my $i = 0;

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

And this is a while loop that will perform the statement pre-evaluation.

===========================================================
Code:

#!/usr/bin/perl
use strict;

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.

===========================================================
Code:

#!/usr/bin/perl
use strict;

my $i = 0;

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

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

===========================================================
Code:

#!/usr/bin/perl
use strict;

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:
They can be put anywhere in the main program.
Any passed-in arguments go to an array called @_.
The subroutine can be called with the ampersand (&) symbol in front of it.
The return statement is utilized to exit the subroutine

Here is an example of a subroutine utilising individual variables.

===========================================================
Code:

#!/usr/bin/perl

sub operatorz {
$addition = $_[0] + $_[1];
$subtraction = $_[0] - $_[1];
$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. We have created our subroutine known as operatorz. Within this, there are several numerical operators and finally a print function. Outside of the subroutine, we are calling the subroutine with our arguments (5,5) which are passed to the subroutine. 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.


===========================================================
Code:

#!/usr/bin/perl
use LWP::Simple;
use LWP::UserAgent;
use strict;

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. As you can see we are using the LWP modules as an API to visit youtube. LWP::UserAgent allows us to initialize a new user agent. We then use $ua->get to fetch our site. 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. 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.

Resources and Practise Sites

Learning
Perl.org
Learn.Perl.org
Perl-tutorial.org
Leeds.ac.uk (Perl v4, still a nice resource)
PerlGuru.com (Forum)
PerlMonks.org (Forum)

Practise

Test bed
Rosetta Code
Euler Project

0 comments:

Post a Comment