Log in

View Full Version : Perl Tutorial!


TheMatrix
June 18th, 2011, 02:32 PM
Table of contents:

Your very first script! (http://virtualteen.org/forums/showpost.php?p=1309827&postcount=1)
Perl Tutorial: Variables, arrays, hashes, subroutines, and simple logic. (http://www.virtualteen.org/forums/showpost.php?p=1310887&postcount=2)


I have decided to teach all who care some Perl! In this post, I will be going over using Perl and a basic "Hello World" script.
Step 1: Prerequisites
This is by far the most important step. Nothing here will work without it.
Perl
If you use Linux, Macintosh(System 9 or newer), FreeBSD, Solaris, or any other *nix system, you probably already have Perl installed.
If you use Windows NT(or above), you will need to install it. You may use ActivePerl (http://www.activestate.com/activeperl/downloads) or any other Perl interpreter. Heck, you could even compile Perl yourself if you really wanted to.
Text editour
Of course you must have a method of actually saving your scripts! Hence, you need a text editour.
Linux
You most likely already have several. Try gEdit or KWrite. Or if you are a command-line person, use vim.

Macintosh(System 10 or later)
I think you use TextEdit or vim.

Windows
There are many. ActivePerl has one, I think. I reccomend that one. Or, use Notepad(when saving, do not forget to save as "script.pl" and set the File type to "All Files").
In addition, on DOS 3.1 or later, you can type "EDIT C:\DOCUME~1\[Your username]\script.pl" in a CMD.EXE window.

Step 2: Starting out your scripts
Once you've got Perl installed, you will need to know WHERE it is installed.
On *nix systems, type the following into a Terminal:
which perl
Remember the output of that, you will need it every time you make a script.
Usually it is /usr/bin/perl, but it can also be in/usr/local/bin/perl, or anywhere else.
On Windows, however, it is somewhere else. I do not know where it would be installed, but I think it will be in C:\Perl\bin\perl, but I could be wrong...
In my sample scripts, I will assume /usr/bin/perl. Adjust your path accordingly.

Step 3: Learning the syntax
Perl has a syntax that is relatively similar to that of PHP, if any of you know PHP. Some basic things to remember are:

A comment is started with a "#"
All commands must end with a semicolon!

Although some things may seem challenging, you'll learn it, eventually.
Also, the style I use in my scripts may not be what you are comfortable with. There is no "correct" style of programming. Use what you think is best.

Step 4: Make your very first script.
So once you've figured out where Perl is, let's use that in a script.
Here is the code:


#!/usr/bin/perl -wT
#This is our very first script!
print "Hello, World!\n";

Save as "hello.pl", to your desktop(you can save it elsewhere, but this tutorial is geared to that path).
Before running it, read the following sections.

Step 5: Some things to remember
There are some conventions I use throughout my tutorials. Some include that I will always add the "-wT" to the end of my pound-bang(#!) line. Those are
some options to send to the Perl interpreter. The "w" stands for "warnings" and the "T" for taint mode. The warnings are useful for debugging your code. The "taint" is for making sure that other data cannot interfere with your script. Although not needed for a "Hello World" script, it can be useful later.
Now, if you look at the sample script, you will see a "\n" at the end of the print statement. This signifies a new line. It is different on most systems.
Windows use "\r\n" for new line
Macintosh System 9 or earlier use "\r" for a new line.
*nix and Macintosh System 10 and newer use "\n" (I use this one in all scripts. Adjust yours accordingly.)

Step 6: Running the script
Now comes the fun part!
Windows
Go to a CMD.EXE window and type CHDIR "C:\DOCUME~1\[Your Username]\DESKTOP\"
Then simply type: hello.pl

Macintosh(System 10 and later), *nix
Open a terminal(On Macintosh, go to "Spotlight" and type "Terminal").
Then type the following commands. Your terminal should then look like this:

[email protected]:/> cd ~/Desktop/
[email protected]:~/Desktop> perl -wT hello.pl


Macintosh(System 9)
I think the same as above, but I don't know where the Terminal would be.

If you get an output of:

Hello, World!

you have done it right. Congratulations!

Step 7: Conclusion
That was all. Quite simple, no?
You are now well on your way to becoming a great programmer: ;)

If you have any questions, comments, or ideas, please post them!

TheMatrix
June 19th, 2011, 06:25 PM
So, did the previous tutorial work out for you?
If it did, then perhaps you should try this one!

Today's tutorial will be about variables, arrays, hashes, subroutines, and simple logic.

Variables
You probably know what a variable is. It is a value that can change.
Variables in Perl start with a $.
An example:

my $string = "Foo";
my $number = 1;

Notice the my before the variable. Although not neccessary, it is a good idea to put this in. It helps both you and Perl distinguish
between local, normal, and global variables. Above are "normal" variables.
There are different types of variables, as well as methods of declaring them.

my $normal = "stuff"; #Normal Variable - Mostly specific to current function
our $global = "something"; #Global variable - Can be accessed anywhere in the script
local $local = "blabla"; #Local Variable - Specific to the current function only.
$main::variable = "fffffff"; #Same as "my"


We'll talk about using the different types of variables later.

Now, how do you access a variable? Quite simple. Take this example script:

#!/usr/bin/perl -w


Arrays
An array is a "list" of data.
Arrays start with a @.
When putting data into it, seperate the values with commas.
For example:
[PHP]
my @rebels = ( "Neo", "Morpheus", "Apok", "Mouse" );

Or add a single value to the array:

push( @rebels, "Tank ); #PUSH a value onto the end of the array
#or
$rebels[4] = "Tank"; #Requires you to know what the next unused space is. Can also be done with the following
#or
my $next = 1 + $#rebels; # "$#rebels" is the number of the last item in the array. Adding one to it gets you the next unused one.
$rebels[$next] = "Tank";

"push" is the best way of doing it.

To delete a value from the array, use the delete function:

delete $rebels[1]; #Deletes "Morpheus"


In the section about logic, I will discuss how to print the values of this array.

Hashes
A hash, also known as an "assosciative array", is used to put data that relates to each other.
Hashes start with a %.
For example:

my %fruits = (
# KEY => VALUE
apple => "Red",
banana => "Yellow",
pear => "green",
);

In the example, you can see that an apple is red, banana is yellow, and a pear is green.
Note: Keys must be unique.

To delete a value from a hash, also use delete:

delete $fruits{apple};


Subroutines
A subroutine is a snippet of code that only gets run when you ask for it to be.
To declare a subroutine, prefix it with sub, and then the function name.
For example:

#The subroutine
sub enter_the_matrix {
print "To enter The Matrix, you must take the red pill.\n";
}

#And now run it.
&enter_the_matrix(); #The ampersand before it is optional, but I reccommend it.

It should print
To enter The Matrix, you must take the red pill.

You can also pass data to the subroutine. You can do this like so:

sub your_opinion {
local( $username, $opinion ) = shift( @_ ); #The @_ array is the array of arguments passed to the subroutine. Shift takes off the first elements of the specified array and returns them.
print "I think that $username is $opinion.\n";
}
my $user = "Sage";
my $opinion = "awesome";
&your_opinion( $user, $opinion );

It would print
I think that Sage is awesome.

Subs are particularly useful for multiple calls.
For example:

sub your_opinion {
local( $username, $opinion ) = shift( @_ );
print "I think that $username is $opinion.\n";
}

&your_opinion( "Sage", "awesome" );
&your_opinion( "Origami", "a pro at signatures" );


You could also have a subroutine return a value:

sub make_random {
local( $range ) = shift( @_ ); #Retrieve the range of the number.
local $number = int( rand( $range ) ); #Make a random integer between 0 and $range.
return $number; #Does not print, just returns.
}

my $n1 = &make_random( 20 );
my $n2 = &make_random( 76 );

print "Our numers were $n1 and $n2.\n";

This should output something like:
Our numbers were 4 and 43.

Simple Logic
Now for the most useful part: simple logic!
Before we begin, though, it is important to remember some things about true and false values.
Perl regards an empty string and 0 as false. Anything else is true.
For example:

sub return_true {
return "this is true.";
}
sub return_false {
return '';
}

#Now we use an if-else loop to check the true.
if( &return_true ) {
print "True works.\n"; #It is true, so do this.
} else {
print "True doesn't work.\n"; #Otherwise, do this
}

#Now we use an if-else loop to check the false.
if( &return_false ) {
#It is supposed to return a false value, so this should not be printed:
print "False doesn't work.\n"; #It is true, so do this.
} else {
print "False works.\n"; #Otherwise, do this if false
}

That should yield:
True works.
False works.


There is also the elsif loop(aka "else if" ).
Use it along with the if and else loops:

if( 1 == 2 ) {
print "Something wacky is going on.\n";
} elsif( 1 == 1 ) {
print "Yaay!\n";
} else {
print "Something is messed up.\n";
}

Should print:
Yaay!

Remember how I said that we would print the @rebels array? Let's do it!

my @rebels = ( "Neo", "Morpheus", "Apok", "Mouse", "Tank" );
print "The rebels:\n";
my $member; #Ready a variable for the loop.
foreach $member ( @rebels ) {
print "$member\n";
}

#OR
#You can also use the $_ variable instead of declaring your own variable. It is set automatically for each iteration
foreach( @rebels ) {
print "$_\n"; #Same as above example
}

Should print:

The rebels:
Neo
Morpheus
Apok
Mouse
Tank

Fun, no?

There is also the while loop. It continues forever until a condition is met or last is called.

#Let's use a counter so that the loop will stop after a while:
my $i = 0;
while( $i <= 9 ) { #Should iterate 10 times
print "$i ";
$i++; #Increments the count. If left out, the loop will continue forever.
}

This will print:
0 1 2 3 4 5 6 7 8 9

Or, you can use the last thing:

while( 1 == 1 ) { #Will continue until stopped
if( &something_is_true ) {
last;
}
}


------------
That's all for now, folks! I will continue this next time!