01 Getting Started
Installing Perl and writing your first script
Introduction
This page is intended to provide the non-programmer with a gentle introduction to the Perl programing language. When you are done with it, you should feel ready to learn more. You will not be an expert, but you will be able to find the information you need to go farther. Beginners and experts alike should feel free to send suggestions about how to improve this tutorial.
Installing Perl
It is very easy to find yourself a copy of Perl 5.10. ActiveState has made binary copies available for each of the major platforms. You can even build your own Perl if you are feeling bold. It's not that hard!
You probably already have Perl 5.10 if you are running Linux and using a recently released distribution. However, I prefer to keep my focus on other options for the moment because Linux distributions may not be completely up to date on Perl libraries - they are generally packaged by volunteers, after all - and I have occasionally mucked up my system when messing with the distro-packaged Perl. It's better to use a special build, set aside from the default Perl which runs so many system scripts.
ActivePerl
This is the officially blessed version of Perl for Windows. It is released by ActiveState, a company based out of Canada.
ActivePerl can be downloaded for free. It comes with a wealth of widely used third-party libraries such as an DBI, LWP, and the XML bundle.
Compiling Your Own Perl
We start by setting up our environment for compiling code. Ubuntu bundles all
the most important components for that task in build-essential.
$ sudo apt-get install build-essential $ mkdir ~/src $ cd ~/src
Next we grab and unpack the latest perl source archive by whatever means we
preferred. I enjoy living on the command line, so I used wget and tar.
$ wget http://www.cpan.org/src/perl-5.10.0.tar.gz $ tar xfvz perl-5.10.0.tar.gz $ cd perl-5.10.0
Now to configure the build process. Running the configuration script with defaults enabled allows us to skip a lot of questions about how we want Perl to be assembled. Let's do that.
$ ./Configure -des
Right. Now we can actually build, test, and install Perl.
$ make $ make test $ sudo make install
Finally, we want to make sure that perl installed where we expected it to
and that our system finds the right one.
$ which perl /usr/local/bin/perl $ perl --version This is perl, v5.10.0 built for i686-linux Copyright 1987-2007, Larry Wall Perl may be copied only under the terms of either the Artistic License or the GNU General Public License, which may be found in the Perl 5 source kit. Complete documentation for Perl, including FAQ lists, should be found on this system using "man perl" or "perldoc perl". If you have access to the Internet, point your browser at http://www.perl.org/, the Perl Home Page.
Creating Perl Programs
The tradition in programming literature is to start by creating a program that prints a simple phrase, such as "Hello, World!" The idea is to give you some clue how much work is involved in creating a minimal program. I am not going to argue with tradition. Not this one, at least. Type the following into your text editor:
1 2 3 4 5 6 7 8 9 10 11 12 | =pod =head1 hello.pl Displays a warm greeting. =cut # Follow some common-sense guidelines for Perl coding. use Modern::Perl; say "Hello, World!"; |
Save the file as hello.pl. We will run it in a few moments, but
first, let's take a quick look at what we've got so far.
POD
1 2 3 4 5 6 7 | =pod =head1 hello.pl Displays a warm greeting. =cut |
POD, or "Plain Old Documentation", is the standard system for documenting Perl
programs. POD directives exist within your application, but are ignored during
execution. They are instead processed by the perldoc application. perldoc
can convert your POD to different formats such as HTML, or simply format and
display the documentation to your screen. Use POD to write about what you want
users to know about your Perl application. A proper introduction to perldoc
is far beyond the scope of this little tutorial, but you can see the potential
usefulness of this tool from the console with a simple command:
$ perldoc hello.pl
You get a simple display showing a formatted version of the POD you wrote.
There is a lot more information you can get about POD and perldoc within
Perl's own POD:
$ perldoc perlpod
There's also an HTML version if
perldoc is not available on your system or you just want to see something
pretty.
Comments
1 | # Follow some common-sense guidelines for Perl coding.
|
On each line, everything from # to the end of the line is a
comment. Perl ignores comments, so they allow you to
communicate with other people who read your code. Comments are
good. When you come back to look at a complex script
after a few months, you might forget what some block of code does,
or why you chose one solution over another. Having the
comments there help to remind you what you were intending, and
generally serve to make it much easier sorting everything out.
use
1 | use Modern::Perl; |
The use statement is incredibly powerful. It effectively changes the way Perl
will behave for the duration of your program. You can get extra functionality
with use by loading a module, or you can significantly change the rules
Perl runs under by loading a pragma.
I will be taking full advantage of the use statement in this tutorial,
because it takes Perl from a strong shell scripting language to an incredibly
powerful programming language.
Oh, about that semi-colon (;): perl uses the semi-colon to separate statements.
Each statement contains a particular instruction for the Perl language. You will
usually - but not always - see Perl code with one statement per line, with a
semi-colon at the end of each line.
Modern::Perl
enables a good deal of that power in a single line. In particular, it tells Perl
that we want to use the features that are available in 5.10, such as say. The
trick with Modern::Perl is that it is not a "core" module. You will need to
install it yourself after Perl is installed.
All right - I know some of you are wondering why I introduce non-core modules as part of "Hello World," which is supposed to be the easiest program out there. The truth is that a great deal of Perl's usefulness comes from external modules. The sooner a new Perl user learns how to install those modules, the better he or she will be. Modern::Perl is a nice small module that has the advantage of enforcing the rules which will teach our new programmer how to write in a style that is appropriate to Perl in 2009.
I'll get off my soapbox now and tell you how to install Modern::Perl.
Installing Modern::Perl With ActivePerl
ActivePerl comes with the Perl Package Manager, a tool to install new modules that are available in various repositories around the world. There is a GUI available, but once again I lean toward the command line:
$ sudo ppm install Modern-Perl
It's the same command on Windows, minus the sudo:
C:\> ppm install Modern-Perl
You should see some feedback as ActivePerl downloads and unpacks the module for you.
Installing Modern::Perl With a Compiled Perl
ppm is great, but it is specific to ActivePerl. Perl in general uses
CPAN, the Central Perl Archive Network. CPAN is huge and
contains the source code for thousands of modules. You should have the cpan
utility after installing Perl. cpan provides an interactive console that
you use to search for new modules and install them.
$ sudo cpan
The first time you run cpan after installing Perl, you will need to get things
set up. Setting up cpan can be a little daunting for a newcomer, and that's why I
often suggest ActivePerl and ppm for a fresh Perl developer. Still, it's
not difficult to configure cpan, and once you do you won't have to worry
about it again.
Thankfully, the first question it asks is whether it should configure itself automatically. Yes, please do that.
One of the things it can't automate is selecting which CPAN servers to download from. You can do this yourself from inside the CPAN console.
1 | cpan[1]> o conf init urllist |
You will get asked a couple of questions about where you are located, and then presented with a long list of mirrors that are available to you. You're supposed to pick a few that are close to you in network terms, but I never have really figured that out. I usually just select 3 or 4 at random from the list presented to me.
1 2 3 | Select as many URLs as you like (by number), put them on one line, separated by blanks, hyphenated ranges allowed e.g. '1 4 5' or '7 1-4 8' [] 10 25 47 |
You will need to commit once you have selected your URLs.
1 | cpan[2]> o conf commit |
One more thing. Installing the latest CPAN::Bundle
will guarantee you the smoothest experience possible when using the cpan shell.
1 | cpan[3]> install Bundle::CPAN |
It will take Perl a while to download and build all the components that are part of CPAN::Bundle. This is a good time to go find out if the coffee has finished brewing.
Done? Okay, let's install Modern::Perl.
1 | cpan[4]> install Modern::Perl |
We're done with cpan now.
1 | cpan[5]> exit |
Installation and Setup Summary For Compiled Perl
In case all of this sounded tremendously involved, here's exactly what I did to get from start to finish:
$ sudo apt-get install wget $ sudo apt-get install build-essential $ mkdir ~/src $ cd ~/src $ wget http://www.cpan.org/src/perl-5.10.0.tar.gz $ tar xfvz perl-5.10.0.tar.gz $ cd perl-5.10.0 $ ./Configure -des $ make $ make test $ sudo make install $ sudo cpan cpan[1]> o conf init urllist cpan[2]> o conf commit cpan[3]> install Bundle::CPAN cpan[4]> install Modern::Perl cpan[5]> exit
Yes, setup is more involved than the ActivePerl approach. I'm comfortable
with that. Now that everything is configured, using Perl and cpan will
be about as straightforward as using ActivePerl.
Let's get back to looking at hello.pl
say
1 | say "Hello, World!"; |
We use say to print things out on a line in Perl 5.10. This time we're
asking Perl to say the phrase "Hello World!".
Hm. I really thought it would take more effort to explain that. Oh well, guess there's nothing left to do but see it in action.
Running it
Now you would probably like to know how to actually run your program.
Save the file you have been editing and switch to a command line. Make
sure you are in the same directory as your script - this should be
as simple as cd *project directory*. Once you are in the right
place, type the following into the command line:
$ perl hello.pl Hello, World! $
All this is kind of cool, but it would be nice to customize it a little bit. Maybe we could change the program so that it says "Hello" to us personally.
1 2 3 4 5 6 7 8 9 10 11 12 13 | =pod =head1 hello.pl Displays a warm greeting. =cut # Follow some common-sense guidelines for Perl coding. use Modern::Perl; my $name = "Brian"; say "Hello, $name!"; |
We use the word my to declare variables. Declaration is
when we tell Perl that we have a variable we plan on using. Modern::Perl
enforces the declaration of variables.
What's a variable? We'll get to that in a second. I'm impatient to see a running program! Save the file, and run it again.
$ perl hello.pl Hello, Brian!
There, I feel better. Let's move on to talking about variables.
Variables
We stored the string "Brian" in the variable name. A variable
is basically just something you want the computer to remember so that
you can get to it when you want it later. You can get a lot more
complicated than that if you want, and a lot of programmers do.
However, this definition should hold us over for a long time.
The "$" symbol at the beginning tells Perl what kind of
information this variable holds. Perl basically has two kinds of
variables:
- Individual things like strings and numbers
- Collections of things like lists and dictionaries
When you start digging in, you will see how broad of a generalization I've just made. Still, I think that this will last us until the end of this article, and the basic idea holds true for a lot of Perl programming.
Anyways. Individual things are also called scalars by people who
think that you don't have enough things to remember. Ah well, we'll
get used to it. To their credit, "scalar" is a shorter term than
"individual thing". Perl makes it easy to recognize a scalar, by
making you prefix all scalar variables with a dollar sign. So
$name is "the scalar variable name", or even "the individual
thing called name". Sometimes I just call it "dollar name" when I'm in a
hurry.
1 2 | my $name = "Brian"; # I'm going to use a scalar variable called 'name'. # It has the value "Brian". |
Anyways, this single line both declares the variable $name, letting Perl
know you plan on using it, and assigning a value to $name, so that Perl will
have something to remember. What happens if you skip one or both of these steps?
It depends, so the best thing to do is try it and see.
1 2 3 4 5 6 7 8 9 10 11 12 | =pod =head1 hello.pl Displays a warm greeting. =cut # Follow some common-sense guidelines for Perl coding. use Modern::Perl; say "Hello, $name!"; |
We've removed the declaration and assignment. Let's see what happens now.
$ perl hello.pl Global symbol "$name" requires explicit package name at hello.pl line 12. Execution of hello.pl aborted due to compilation errors.
Because we insisted on Modern::Perl, Perl politely informed us that it found
some mention of a variable called $name that we never told it about. Since
that is a rude way to be in a well-behaved program, Perl quit
without even running the code.
Okay, what if we declare $name but never assign a value to it?
1 2 3 4 5 | # Follow some common-sense guidelines for Perl coding. use Modern::Perl; my $name; say "Hello, $name!"; |
This time Perl runs, but not without complaint.
$ perl hello.pl Use of uninitialized value $name in concatenation (.) or string at hello.pl line 13. Hello, !
Since $name has no value, Perl has nothing to put in that string. That's
exactly what it puts there: nothing.
Those warnings and fits of anger are actually very helpful. They make it very easy to figure out where some of the most common sorts of errors happen. Things like misspelling a variable name or forgetting to set a variable get flagged by Perl. That simplifies the task of debugging and maintaining programs that you write. Think about your challenge if this error was in the midst of a 10,000 line program that looped through a database. These are the situations where Modern::Perl is vital.
With Modern::Perl enabled we have told Perl to behave more like a powerful application programming language with Perl's latest features instead of as a quick and handy tool for system administrators. Decide for yourself whether that transformation is important to you, but all of my code in this tutorial will use Modern::Perl.
