Perl - University of Oklahoma



Introduction to Perl

by Tim Supinie

This document is intended to give you a sort of crash course in writing a Perl script (and to save you having to go out and by a $40-50 book.) In many ways, Perl is similar to C, but it is different in a few key ways. First off, C is a complied language, and Perl is an interpreted language. What does this mean? In C, you have a source file which a complier takes, translates into a bunch of 1’s and 0’s, and sticks into an executable, which you then run via the operating system. With Perl, however, you have a program somewhere on your machine (the interpreter) which takes your human-readable code (“human-readable” is a loose term) and compiles them into byte codes that are read by the interpreter, which then executes commands.

We will be using the vi text editor, if you need help using it, ask me.

The Basics

First to start out, open up a terminal window (or login to your web space if you’re working from home) and type the command

vi firstScript.pl

This will open the vi editor with the new file firstScript.pl (.pl is a common extension for Perl scripts.) The very first thing you need to do in the script is tell the operating system where the Perl interpreter is. To do this, enter append mode by typing the a key and then type the following:

#!/usr/local/bin/perl

The path /usr/local/bin/perl may differ from system to system, but on the NWC servers, it’s all the same. You must have this line at the beginning of every script or the operating system will not run it.

One thing that is different between C and Perl is that Perl does not require you to have a main function. So we can get straight to the meat of the program by typing

print “Hello World!\n”;

This prints the string “Hello World!” followed by a new line character to the screen. Pretty straight-forward. Let’s run it. Hit the escape key to leave append mode and then type :wq. This is the vi command to write to the file and quit the editor. Before we run the script let’s take a quick aside. Type ll to provide a long listing of all the files in the directory. The very first column on the left indicates what are called permissions, which basically specifies which users are allowed to do what with your files. There will be ten characters in the permissions. The first character indicates whether or not it is a directory (indicated by a d.) The next three characters indicate the permissions for you (the user.) An r indicates reading permission, a w indicates writing permission, and an x indicates executing permission. The next three characters are permissions for users in your group, and the last three characters are permissions for everybody else. You may notice that the script we just created, firstScript.pl, is not allowed to be executed by anybody. We need to change that, so type

chmod 744 firstScript.pl

This changes the permissions such that you can read, write and execute the file, and everybody else can only read it (that’s what the 744 means. It’s somewhat complicated and difficult to remember, but if you want me to explain it to you, I can.) This step only needs to be done once for each script, but the operating system will not run your script if the permissions aren’t right. So, now we’re finally ready to run the script. Type

perl firstScript.pl

or alternately,

./firstScript.pl

Sometimes the latter method won’t work properly, so using the former one is probably a good practice, as it always works. So, did it work? If not, go back and check to make sure you typed everything correctly. Once we get everything working, it’s time to move on. From now on, I’m going to assume you know everything that’s been covered so far (how to run a script, vi commands, etc.) If you don’t remember how to do something, go back and look it up or ask me.

Variables and Such

A variable is a container for a value. Another way that Perl differs from C is in its variables. C requires that you declare all your variables with syntax like

int numberOfSongsOnAlbum = 8;

float lengthOfAlbumInMinutes = 43.52;

Perl, however, does not make a difference between integer and float variables, or even between number-type variables (ints and floats) and string-type variables (chars). This means that the following is perfectly acceptable in Perl:

my $numberOfSongsOnAlbum = 8;

my $lengthOfAlbumInMinutes = 43.52;

my $nameOfAlbum = “Leftoverture”;

Perl doesn’t even require you include the my statement, but it is good practice to declare your variables so you can keep track of them. The $ on the beginning of the variable must be there every time you reference a variable, and it tells the Perl interpreter it’s looking at a scalar (as opposed an array, which I will talk about later, or a hash, which I won’t get into here.) So, armed with this knowledge, open up firstScript.pl again. You can delete the Hello World statement if you wish (do this by hitting escape to exit append mode, moving the cursor to the line you wish to delete, and typing dd.) Now type the following:

my $firstNumber = 3;

my $secondNumber = 4;

my $numbersAdded = $firstNumber + $secondNumber;

my $numbersSubtracted = $firstNumber - $secondNumber;

my $numbersMultiplied = $firstNumber * $secondNumber;

my $numbersDivided = $firstNumber / $secondNumber;

my $numbersConcatenated = $firstNumber . $secondNumber;

print “Added: $numbersAdded\n”;

print “Subtracted: $numbersSubtracted\n”;

print “Multiplied: $numbersMultiplied\n”;

print “Divided: $numbersDivided\n”;

print “Concatenated: $numbersConcatenated\n”;

Okay, so the basic mathematic operations are the same as C. But what’s with this “concatenated” business? And what’s going on in those print statements?

The . (concatenation) operator tells the Perl interpreter to treat $firstNumber and $secondNumber as strings, not numbers, and stick them together like you would combine two strings.

One of the nice features of Perl is that it allows you to interpolate variables in string literals, as in the print statements above. Instead of the text $numbersAdded popping out when you run the script, the value of $numbersAdded will be in its place.* So save to the file, quit vi and run the script. What happens? It should look something like this:

Added: 7

Subtracted: -1

Multiplied: 12

Divided: 0.75

Concatenated: 34

Now say you had the following script. What would do you think its output would be?

#!/usr/local/bin/perl

my $stringPart1 = “Boomer”;

my $stringPart2 = “Sooner”;

my $string1 = $stringPart1 + $stringPart2;

my $string2 = $stringPart1 . $stringPart2;

print “String 1: $string1\n”;

print “String 2: $string2\n”;

At first glance, $string1 and $string2 look like they should contain the same value. But the + operator tells the Perl interpreter to treat the two values as numbers. Not a problem if they really are numbers, but if they’re strings the Perl interpreter puts zeros there, since a string can’t be represented as a number. So the output would be

String 1: 0

String 2: BoomerSooner

Branching

Branching (if statements) allows you to choose what your code does based on pre-existing conditions. Branching in Perl is very much like C, with only one major difference that I can think of. Open up firstScript.pl in vi again. If you wish, you can delete code from the first couple sections. To delete multiple lines in vi, press escape to exit out of append mode, put the cursor on the first line you wish to delete, and type [xx]dd, where [xx] is the number of lines you wish to delete. If you realize you’ve deleted too much, you can press either p (paste) or u (undo) to put the text back. Now that you have firstScript.pl open, type the following:

my $firstNumber = 3;

my $secondNumber = 4;

my $thirdNumber = 3;

if ($firstNumber == $secondNumber) {

print “The first and second numbers are equal.\n”;

}

elsif ($firstNumber == $thirdNumber) {

print “The first and third numbers are equal.\n”;

}

elsif ($secondNumber == $thirdNumber) {

print “The second and third numbers are equal.\n”;

}

else {

print “None of the numbers are equal.\n”;

}

So far, so good. One of the main differences from C is that C has the else if statement, which in Perl is combined to a single elsif statement. Save, quit and run. The output should be something like this:

The first and third numbers are equal.

The major difference between C and Perl in terms of if statements is that C will not allow you to compare strings using the standard operators. You need a set of functions to do string comparisons (you will get to this later in the semester.) Perl does allow you to do string comparisons using operators, but again, there’s a difference between operators for numbers and operators for strings. If you wanted to test the equality of two strings, you would use the eq operator, as in the following:

my $firstString = “Tim”;

my $secondString = “Supinie”;

my $thirdString = “Tim”;

if ($firstString eq $secondString) {

print “The first and second strings are equal.\n”;

}

elsif ($firstString eq $thirdString) {

print “The first and third strings are equal.\n”;

}

elsif ($secondString eq $thirdString) {

print “The second and third strings are equal.\n”;

}

else {

print “None of the strings are equal.\n”;

}

The following is a table of Perl equality operators for both numbers and strings.

| |Numerical Operator |String Operator |

|Equal |== |eq |

|Less than |< |lt |

|Greater than |> |gt |

|Less than or equal to |= |ge |

|Not equal to |!= |ne |

Arrays and Looping

Arrays may be a new construct for you, but they’re relatively simple once you get the hang of them. When you have just an ordinary variable, such as $secondIncubusAlbum, that would be considered a scalar (just one value, like the scalars they told you about in your science classes.) You can string a bunch of related scalars together using an array. Individual scalars in the array are called elements, and each element has an index that tells its location in the array. So instead of having separate variables for $firstIncubusAlbum, $secondIncubusAlbum, and on down the line, you can simply have an array @incubusAlbums that bundles them all together. The @ symbol at the beginning tells the Perl interpreter it’s not dealing with just one scalar anymore, but it could be any number of scalars bundled together. Individual elements in the array are accessed with the syntax $incubusAlbums[2], which will return the second element in the array @incubusAlbums. Notice that when you access an element, you stick the $ on the front when you’re accessing an individual element. This is because you’re just talking about a single element in the array, and not the array as a whole. Arrays can be particularly useful when you don’t know how many of something you will be dealing with because in Perl, because their sizes are fairly flexible (this is not true in C.)

Loops allow you to execute commands multiple times without having to write them all out. They are really, really useful when dealing with arrays for a couple reasons. First, it saves you a lot of typing. If you need to do commands multiple times in a row, put them in a loop. Second, often times, you don’t know ahead of time how many elements are in the array. Many times, it could be any number of elements, impossible to predict beforehand. So you can tell the Perl interpreter to repeat the commands multiple times until you’ve done it to all the elements in the array. Loops are virtually the same as C in terms of syntax. Open up firstScript.pl (again, deleting old stuff if you wish) and type

my @incubusAlbums = (“Fungus Amongus”, “S.C.I.E.N.C.E.”,

“Make Yourself”, “Morning View”,

“A Crow Left of the Murder ...”, “Light Grenades”);

for (my $counter = 0; $counter ................
................

In order to avoid copyright disputes, this page is only a partial summary.

Google Online Preview   Download