Synfire's Quick Guide to Perl

This is a quick tutorial to Perl. It is not a very indepth one and it don't cover every aspect of perl, but it does work as a "quickie" to help you get familiar with perl.

This tutorial is set up in a certain fashion that makes things as simple as posible for me and you.

First I list many of the basic syntax of functions and a quick description on the usage.
Then, after I have gone over a few I will give an example source code for you to play around with.
I believe the best way to learn anything is through learning the usage and then putting the usage to action. If you just want to write perl code then you are in the right place.
If you want to know perl then I suggest reading a copy of Programming Perl or Learning Perl - Advanced Perl series to give you a great understanding of this wonderful easy language.

When you start out a perl script you should make a habit to always include the execution path, or the path of the perl interpreter following a #! .
This is known as an exec() call. exec is used to keep you from having to define the interpreter on the command line every time the program is executed. On most linux computers the command will be:

#!/usr/bin/perl

Comments - a comment is a section of text describing what the program is doing.
The reason for comments is so your source code can be understood by other people, or even you after along time of not working on that source.
The syntax for a comment in perl is very simple:

# This is a comment.
# It is began with a # to let perl know not to read this text.
# this text is infact skipped when the perl script is executed.
Scalars - a scalar is a variable that, much like in math, holds information. This information can be a number, a string, a shell commands output, or even a large page worth of data. the syntax of a scalar is:
$calar = 1; # This assigns the numerical value 1 to $calar.
$calar = "Hey!"; # assigns the string value Hey! to $calar.
$output = `who -HTu`; # This assigns the output of the who -HTu

# command to $output.
$text = EOF;
All of the text here is now in the
text scalar. You can even put other
scalars in here and add the output to
this text. To end this you type EOF on a
line by itself.
EOF
print() - print is used to send data into something. If nothing is specified then it defaults to STDOUT, or in english prints it on the screen. If you specify a 'file handle' ( or as you will learn later a short name you give for a file or socket ) then print sends the data to that file handle.
print "Fine weather we are having today!\n";
# This prints everything in quotes to the screen and the \n
# or better known as a 'newline' starts you out on a new line.

print OUT "This is going to the File handle OUT...\n";

# I just wanted to show you this, I will explain it better later.
Now that we have gotten this far, here is an example program that covers everything you have seen so far:
#!/usr/bin/perl

# This program simply welcomes the current user on a
# Linux Box.
$me = `whoami`;
$welcome = EOF;
Welcome $me,

How have you been today?
We have been waiting for you all day!
EOF

print $welcome;
This program prints the following text when the user admitch216 runs this program:
Welcome admitch216,

How have you been today?
We have been waiting for you all day!
But if user djdon1994 executes it says:
Welcome djdon1994,

How have you been today?
We have been waiting for you all day!
So you think your pretty kewl now that you can make a file print something specific that changes with each user to the screen just because they type it's name at the command prompt. Well your not! ;)

But give me a little longer and a few more examples and you will be writing some pretty kewl stuff. Of course you will become somewhat of a computer geek, but who said that was a bad thing!

STDIN - STDIN is a handle for Standard Input. This is for reading information from the keyboard into a specified target up until the first \n character, usually a scalar or an array.
$calar = <STDIN> ;
chomp() - chomp is a function used to remove a \n off of a scalar. This is for, when assigning input from STDIN, a \n is added to the end of your scalar by the user pressing enter. chomp deletes that \n off the end of the scalar.
chomp($calar);
expressions - expressions are values that return either true ( 1 ) or false ( 0 ). When programming in perl, you will use expressions alot so it is best if you learn them well. Here is a list of operators that you can use in your expressions:

LIST OF OPERATORS

Numerical:

**  Exponental ( 2**3 is the same 
                        as 2 X 2 X 2 )
+   Addition
-   Subtraction
*   Multipication
/   Division
%   Modulus ( the remainder )
<   Less Than
<=  Less Than or equals
==  Equals
>=  Greater Than or equals
>   Greater Than
!=  NOT equals


Strings:

.   Concatenate ( "hey"." "."there!" is the 
                      same as "hey there!" )
eq  Equals
ne  Not Equals
lt  Less than
gt  Greater than
le  Less than or equals
ge  Greater than or equals
x   repetition ( "ha"x3 is the same 
                             as "hahaha" )
An expression usually uses these operators to return a numerical value. Here are a few examples of some expressions:
$c = $a + $b;
$d = ("This"." "."is"." "."Perl!")." ".("techniques");
increment and decrement - the incremement operator (++) increases the value of the associate by 1. The decrement operator (--) decreases the value of the associate by 1. If the operator is in front of the associate then the associate is changed then used, otherwise, if the operator is after the associate then the associate is changed after it is used.
$associate++;
++$associate;
$associate--;
--$associate;
if/else statements - If/else statements are used to make a code execute one thing 'if' an expression returns true, and another thing if the expression returns false.
if ($a eq $b) {
print "$a and $b are the same\n";
} 
else {
print "$a is not equal to $b\n";
}
Infinate Loops - before we start with the control structures (loops) I am going to explain what an infinate loop is. An infinate loop is a loop that is set to continue forever. In terminal programs you probably won't use this. But in GUI's you have to be able to set an infinate loop for the GUI to run without failing. In the following loops the infinate loop for each will be precieded by an *.

while - the while statement repeats a block of code until while returns a false value back to the program.

while ($a < $b) {
print $a;
$a++;
}

*
while(1){
print "Loop ";
}
do...while - do... while is used the same as the while loop except it forces the code to executed atleast once:
do {
print "1 Print Names\n";
print "2 Add Name\n";
print "3 Exit\n";
print "Enter your choice: ";
$choice = <STDIN> ;
} while ($choice == 1 || $choice == 2);

* do{
print "1 Print Names\n";
print "2 Add Name\n";
print "3 Exit\n";
$choice = <STDIN> ;
}while(1);
for - a for loop, next to while, is probably the most used loop there is. The for loop takes 3 arguements, an assignment, an expression, and an execution. When for is ran it executes the first argument, usually its assigning a scalar. Then it test the second arguement, if the second arguement is true then the body of the for loop is executed. After the execution the third agruement is executed and then the second is tested again.
for($i = 0; $i < 10; $i++) {
print $i;
}

*
for(;;;){
print "Loop ";
}
arrays - an array is much like a scalar but it holds more data. An array is a collection of 'elements' that can hold values.
@rray = qw( 1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
print $rray[1];

Ok to explain this a little more, first the @rray is assigned all the values in the parenthesis, each one going to a specific element starting from 0. So, if you were to have this in a program and executed it then the print $array[1] wouldn't print 1 but it would print 2 cause two is in the second spot and the array counts from 0.
The qw() is used to make writing the program quicker. Normally you would have to put quotation marks around each element, but with qw() you don't. Also notice that when I executed the array element 1, $rray[1], I used a $ instead of @. This is because an element is treated just like a scalar and the array is not.

foreach - foreach is an array based loop. It executes a block of code for every element in an array. Lets take the array from above, and place it in the foreach loop:
foreach $e (@rray){
print $e;
}
When this code is executed the array passes the value of it's first element into $e, then the print $e is executed, afterwards the array passes the value of it's second element into $e. This is repeated until each element has been passed.

There are some functions that are personal to arrays, among these are; reverse(), push(), pop(), unshift(), shift(), and sort().

Here is an example of each with a comment on what they do:
@abc = sort(@bac); # this arranges the elements in ASCII order
@backwards = reverse(@forward); # this assigns @backwards
# the elements of @forward in reverse.

push(@rray, 1); # this puts the value 1 to the end of the array
pop(@rray); # removes the last element of @rray

unshift(@rray, "first"); # this puts the value "first" at the beginning
                         # of @rray.
shift(@rray); # removes the first element of @rray
hashes - a hash is like an array in the fact that it holds multiple sets of data, but it is different in the fact that it holds it's data in Key - Value pairs.
%hash = qw(
President, Steve Miller,
Vice President , Dany Autry,
Executive, Chris Mason,
Accountant, Micheal McConell,
System Administrator, David Hart,
);

print $hash{"President"};
Here is a quick little, NOT Secure, login script.
#!/usr/bin/perl

# login.pl - this program finds out the current 
# user and tells wether or not the user is allowed 
# to use the program then if they are it asks them
# for a password and runs the password through 
# a light homemade algorithym. For this program 
# to be secure you would have to write a seperate
# user/password file that has restricted access, 
# then the program takes the information from 
# the file and runs it through a cypher.

$user = `whoami`;

%passwd = qw(
    Jmill   3hiefwh323i
    Cdun    312i54hjfeds89ae
    Mingr   90fewi00f09u0fdsh89fy8eh
    Digit   8329hufe8waiusf843ue
);

print "Password: ";
$pass = <STDIN> ;
chomp $pass;
$enc = (($pass + $user) * 4);
$encrypted = (($enc**2) / 3.14);
if ($encrypted eq %passwd{"$user"}) {
    print "YOU ARE WELCOME HERE!\n";
} else {
    print "Sorry $user, your not welcome\n";
}
Just like arrays, hashes have some special functions that only they can use. These are delete(), keys() and values().
@hash_keys = keys(%hash); # assigns all the keys of %hash
                          # to @hash_keys.
@hash_values = values(%hash); # assigns all the values of
                              # %hash to @hash_values.
delete($hash{"Jmill"}); # deletes the hash key/value pair Jmill.


Concerned about phishing or want to know more about it? Then read our fake logins page.