PDA

View Full Version : Perl Basics


jazzer01
05-18-2007, 11:33 PM
Sorry I havn't posted a tutorial in a while - have been busy with some freelance work (just scored a $1,000 job :)), so I havn't really had a chance to write anything.

These are some Perl tutorials I wrote when I used to program in Perl a few years ago - I havn't really written in Perl in a while, but I thought they might be useful if anyone is looking at learning Perl, or wants to make a decision if to learn Perl or PHP.

If anyone else has any tutorials to add, feel free :)

Edit: Reading through these tutorials, its obvious I wrote them a few years ago!! They aren't great, but I hope they will still give you an idea of the Perl basics, and if Perl is for you!

jazzer01
05-18-2007, 11:38 PM
In order to learn perl, it is good to get to grips with the basics. There are different things to learn, like stuff about variables to learn before you start hacking out scripts!

PERL DATA-Numbers and strings

When you use perl, it needs data or information to work with, and it also outputs alot of data. This can come in three forms, numbers, witch, just happen to be one or more digits put together to express a value

or they could be strings, strings are letters, or words put together. You should always put strings in quotes, but we will get on to that later.

Unlike other languages, you dont have to say what the given data is, if it is a number, or a string, perl works this out by looking at the operators, or functions, given to the piece of data.

For example, we will use 5+6 As you use a mathmatical operator (+), perl takes the data to be numbers, and so would return 11, likewise, if you took 'orange'+'soda' , you would get 0

now, take this 'orange'.'soda' . This uses the concatenation operator (a period), this adds words together, so perl takes anything with that function to be a string. This is why 5.6 Will give you 56.

Variables
in Perl, you have two types of data, Constants, that always stay the same, and variables.

Variables are placeholders for data. The data in these can be changed, which is good for dynamic pages!!. A variable is basically a labe for some data, and is always started by a $, %, or an @ sign, depending on its type.

A scalar variable is the one with the $ sign, as in $calar. these just contain a single string, like a name or somthing. To assign data to a scalar, use, $variable_name = 'data'

An array variable is the one with the @ sign, as in @rray. these just contain a series of strings, this is often used to read lists of data from a file, as each seperate line is an item in the array. To assign data to an array, use, @variable_name = ('data','data2','data3',72) each item must be seperated with a comma

A hash variable is the one with the % sign, and i havent a clue why it uses a %!!!. these are like arrays, but each item has a key. This can hold a series of pieces of info about somthing. To assign data to a hash, the easiest way is to use the => function thus, %variable_name = (name => 'Name',Key2 => 'key2data')
again, each pair is seperated by commas. The first part is the key, the name of that item, and the data is the second bit. Note, the data MUST be quoted. The key, if used thi way, does not have to be quoted
Quotes

In the previous examples, i have used a single quote for each thing (') however, sometimes you need a double quote (")

double quotes show that data needs to be processed, or interpolated. Such things are variables, as they variable needs to be processed, to print its content. eg.

print "I am $gender";
the print statement tells perl to Print the given data, in this case to the browser. this would therefore show I am and then whatever the content of $gender was.

However, if you used single quotes, it would not be interpolated, and so
print 'I am $gender' ; would literally print I am $gender.

In order to use quotes inside your data, you use backslash (\) this can escape any special meaning to an object, so it can also be used to allow you to show $, @ or %'s: (\$, \@, \%)

Other important notes
This is the final piece of our basic knowlage, all the odds you MUST remember before starting

1) shebang- All perl scripts start with a thing called a shebang line, this displayes where the perl interpretor (the thing to read the perl script) is located on your server. It starts with a SHarp(#) and a BANG(!) and is followed by the PATH to the perl decoder eg.

#!/usr/bin/perl is a common one. This must be the FIRST line in your script

2)comments- comments are shown with a # in perl, just type #your comment here

3) All statements, apart from comments, the shebang line, and conditional lines, which we will come on to, must have a ; at the end. As whitespace means nothing in perl, the only way to show the ned of a statement is with a semi-colon (;)

4) every perl script must create output, but to do that,it wants to know what type of output you are using, so, near the top, before any other print statements, type
print "Content-type: text/html\n\n";
this tells perl, that you are outputting a webpage.

jazzer01
05-18-2007, 11:42 PM
As I have said, the scalar variable is shown by a dollar sign ($) and holds one string or number

To assign a piece of data to the scalar, use the code:
$scalar = "data";
Where scalar is the name of the variable, and data is the info for the variable to contain.

It is also a good idea to declare a variable. This is so it cant be used by outside scripts. It is really simple to do. All you do is add my before you type the variable. eg.

my $variable = "data";


Maths with a scalar variable

Yes, Perl is a good mathmatition too! It can do a lot of mathmatical functions, usng some simple commands.

* Multipled by
/ Divided By
+ Add
-subtract

It is really simple to do these.
All you do is take the first number, it can be in a scalar, or it can be by itself. then type your operator. Then type the second number.

an example of this could be:

#!/usr/bin/perl

$first = 10 ;
$second = 21 ;

##add together first and second

$first + $second;

Okay, so that is kind of usless, as you havent done anything with the sum. But what you can do is assign the sum to a new variable, by using
$sum = $first + $second;
where sum is the name of the new variable. Then this can be used to print out later.

You can also use brackets to make perl do the sum in the order you want. For example 3+2*5 is 13 beacuse, according to maths rules, you do multiplication before addition. however, (3+2)*5 is 25 because barckets are always done first.

Lets add this to the form processing we can now do. Lets assume we have an order form that someone can fill in, and we want to work out the total, and tell the user what that is. The form Has a text box for the quantity of each item and the name is the name of the item. For this excersise, we will say all items are $5

The perl script could look something like this:


#!/usr/bin/perl

use CGI ':standard';

#get the quantites

my $eggs = param('eggs');
my $bacon = param('bacon');
my $tuna = param('tuna');
my $coke = param('coke');

#Print out their order
print "Content-type: text/html\n\n";

print "You ordered:";
print "<li>$eggs eggs";
print "<li>$coke cokes";
print "<li>$tuna tunas";
print "<li>$bacon bacons";
print "

and your total comes to:";

#calculate total
$total = (5 * $coke) + (5 * $bacon) + (5 * $tuna) + (5 * $eggs);

print "Your total is $total";


Advanced Maths With Perl
With perl, not only can you do simple maths, you can do things such as powers and other things.

POWERS
powers, such as squared and cubed are also possilbe to do in perl.

To do it, type $number ** 3 Where 3 is the number you wish to raise to the power of. So if $number = 4, that would be $number**3 in written maths which is 64. As in addition, you can assign this to a variable $newnumber = $number ** 3

OTHER FUNCTIONS

The one other main set are:
square root: function(sqrt $number)
integer: function(int $number)
cosine: function(cos $number)
sine: function(sin $number).

Well, thats all the main ones!


JOINING TWO OR MORE STRINGS

If you have a and b, but you want ab, in perl, there is a simple way to do it. Its a ., yep a simple period (.)

eg.
$a = 'moose';
$b = 'hoose';
print "$a.$b";

and this would give you moosehoose

you can also use normal text in this eg.
print "I live in a moose.$b";

INCREASEING AND DECREASEING VARIABLES

To Increase(or decrease) a number by one, you can use a simple opporator, ++ or --

++$n will increase the RESULT (what it is) by one
$n++ will increase the return value of one, but not the result

likewise --$a will decrease the result and so on.

This is useful for things like counters and could also be used, if done properly, as a password incriptor, eg
(take $password to be the password)

$last = chop ($password);
$pen = chop ($password);
$penpen = chop ($password);

++$last;
--$pen;
--$penpen;
--$penpen;

$password = $password.$penpen.$pen.$last;


(You will learn about the chop command later, but for your information, it takes off the last character of the string, and in our case, assigns it to a variable, which is then modified and returned to the whole variable.

NOTE: I do not reccomend this as a 100% safe encryption method. It is only a comment on how the ++ operator can be used. We will not accept responcability from this encyption method getting anything hacked!! :)

jazzer01
05-18-2007, 11:50 PM
If your going to use perl, then there is a good chance that it is so that forms people fill in can be used in databases or suchlike. In order to do this, the script needs a section of code to do this. We could go through all the trouble of doing this, and i will provide the code at a later date, but there is a module, called CGI.pm that is so common, it is now a defult part of perl, and guess what?? It contains a nice bit of coding we can call upon to do it all for us!

To call the module, we need to first add a little bit of code to our scripts:

use CGI':standard';


The param subroutine

The section of CGI.pm we are going to use is called the param subroutine, as it gets data from the form. It takes one argument, which is the name of the field to get the value from.

to do this, we use a small bit of code, to call the param subroutine:
$data = param('name');

Now, this is how to break it down. $data is the name of the variable, you can change data to whatever you want the variable that contains the data to be called, eg. $jack.

param() calls the param subroutine, and it uses the paramater 'name', which is the name of the field we wish to get the data from. This is case sensitive, so be careful.

NOTE: IT is somtimes possible, ie with checkboxes to have more than one result, if they check 2 check boxes, then you will have two bits of information. To sort that, you use an array, because, as you know, arrays contain more than 1 piece of data. so to do that, you need to change the scalar symbol to an array one i.e. @data = param('name')

SO now, you have the data in a variable, you can now do things such as print it, or save it to a text file(we will come on to that later).

SAMPLE CODE

#!/usr/bin/perl
use CGI':standard';

#get the value of the name field
$name = param('name');

#get the value of the email field
$email = param('email');

#Print out the web page
print "Content-type: text/html\n\n";
print "<html><head></head><body>";
print "You entered the name $name";
print "You entered the email address $email";
print "</body></html>";

wajiguqu0223
09-14-2008, 07:38 PM
Sep 14, 2008 (Sawf Interestingness) - Britney Spears plans to piddle a spectacular arise indorse with a lively exhibit at the Pearl House in the EQ2 plat (http://ugamegold.com/c_EQ2-Sale/)Palms Cassino Apply in Las Vegas on New Year's Eve. Britney's new medium is potential to be released by the end of December.