Perl Primer for Mac OSX Users

This Perl Primer is aimed at Mac OSX users who want to learn how to start programming in Perl. It aims to give you enough information to get started writing and running Perl programs on OSX, but won't teach you anything much about the Perl language. There are plenty of good introductions to the Perl language already out there, like this one. For this primer, we'll assume that you don't know anything much about Perl, programming, or the command line, but that you do at least know your way around OSX (e.g. you know what the applications folder is and how to find it). So if you're a web designer or PHP programmer who wants to get started programming in Perl (Hi Steve!) then this is for you.

The Command Line

Top Close Open

Perl programs are usually (but not always) run from the command line. In Mac-speak, the command line is usually known as the Terminal application. In the world of Unix (on which OSX is built), people often call it a command line shell, but it's the same thing (or close enough to make no difference). You can find the Terminal in the Applications/Utilities folder. You might want to drag it to the dock so you've got easy access to it in future.

Run the Terminal app and you should see a new window appear with a command line prompt waiting for you to type something. The prompt that you see will usually depend on your machine name and user name. On my machine (called "shiny"), the default prompt for me (user "abw") looks like this:

shiny:~ abw$

To avoid any confusion, we'll follow the common convention of showing the prompt as just $, like this:

$ 

Type which perl and hit ENTER (from now on we'll take it as read that you need to hit ENTER at the end of each line). Remember, you don't need to type the $ at the start of the line. The examples below show what you need to type in green. The output that you should see is shown in blue.

$ which perl
/usr/bin/perl

The command you've just typed is asking your Mac for the location of perl on your system. It should respond by printing the location as /usr/bin/perl. Now type perl -v. This runs perl with the verbose (-v) option. Perl will response by printing its version number and a copyright message.

$ perl -v

This is perl, v5.8.8 built for darwin-thread-multi-2level
(with 1 registered patch, see perl -V for more detail)

Copyright 1987-2006, 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.

Writing Your First Perl Program

Top Close Open

The job of the perl program is to run the Perl programs that you write. We call this kind of "program that runs other programs" an interpreter. It reads your Perl program and interprets it into a language that your computer can understand.

Perl programs are written in plain text files. Mac OSX comes with a very simple TextEdit application (in your Applications folder) which you can use to create plain text files. However, it's not really cut out for any kind of serious programming and you'll do much better using an editor that's been designed specially for that task. I can highly recommend TextMate. Although it's not free, it's very reasonably priced and you can use it free for a month to evaluate it (and no, I'm not on commission :-) There are plenty of other text editors available for the Mac (both free and commercial). Wikipedia has a list to get you started.

Having got yourself a text editor (TextEdit will do just fine for now), type in the following Perl program and save it to a file called hello.pl (by the way, if you're using a UK keyboard, the # character is Alt+3). You might want to create a new folder for your perl programs to keep them separate from everything else. We'll assume in these examples that you create a folder called perl under your home folder.

#!/usr/bin/perl

use strict;
use warnings;

print "Hello World\n";

The first line of the program is a magical incantation that tells Mac OSX how to run this program. We're telling it to use the perl interpreter (located at /usr/bin/perl) to make sense of it. The next two lines should appear in every Perl program you write. The first puts Perl in strict mode, the second turns on all warnings. Trust me, you want these. Even the Perl gurus use them religiously, so it's nothing to be ashamed of. The final line of the program (or the only real line of the program if you discount the first few lines of pre-amble) prints the message Hello World to the screen. The \n at the end of the message is a special code (usually called an escape sequence) that Perl interprets as a newline character (another common one is \t which inserts a TAB character). The message is quoted using "double quotes" so that Perl can tell where the message starts and ends. You can also use 'single quotes' in Perl, but \n, \t and other escape sequences don't work inside them, so double quotes is what we want here. Programmers refer to these quoted things as strings because they represent a string of characters.

Running Your First Perl Program

Top Close Open

Now that you've written and saved your first Perl program you can run it from the command line. But first we have to find it. If you saved your Perl program in a new perl folder then you'll need to type this at the Terminal prompt:

$ cd perl

The cd command tells the terminal to change directory to the perl directory. A 'directory' is the Unix name for what you know as a 'folder'. Same thing, different name. If you saved it in a directory several levels down then use / to separate each directory name. e.g.

$ cd perl/scripts/test

If you lose track of where you are, the pwd command will print the working directory.

$ pwd
/Users/abw/perl

Once you've navigated yourself to the directory where your Perl program is saved, you can use the ls command to list the files in that directory. You should see your hello.pl file listed.

$ ls
hello.pl

You can now run your Perl program by calling the perl interpreter and giving it the name of the program file which in this case is hello.pl. Your Perl program should respond by printing the Hello World message and a newline.

$ perl hello.pl
Hello World

One final enhancement is to make your new Perl program executable using the chmod (change mode) Terminal command:

$ chmod u+x hello.pl

This tells Mac OSX that the user who "owns" the hello.pl file (i.e. you) can execute (i.e. run) it as a program. Now you don't need to put perl in front of your program name. However, you may need to be a bit more precise about exactly where the program is by putting ./ in front of the program name.

$ ./hello.pl
Hello World

The . prefix is Unix-lingo for "the current directory" and / is the regular path separator that we use when talking about files and directories. So the example above is simply telling Mac OSX that it's the hello.pl program in the current directory that we want to run. The reason for this is because Mac OSX has its own idea about where executable programs live (e.g. your applications folder) so it goes looking there first. It doesn't usually bother looking in the current directory (unless you've specifically configured it to do so) so it needs that extra clue to find the right file. Alternately, you can spell out the full path to the program, but that's obviously a little more tedious:

$ /Users/abw/perl/hello.pl
Hello World

Congratulations! You've now written and run your first Perl program. At this point you might like to try out some more of the examples in this tutorial, or read more from the Perl Introduction page.

Installing Perl Modules

Top Close Open

The best thing about Perl is CPAN. CPAN is the Comprehensive Perl Archive Network. In short, it's where you go to find Perl software. Perl software is distributed as Perl modules. There's nothing particularly special about Perl modules. They're written in plain text files which you can load up into your favourite text editor to see how they work. Perl modules typically have a .pm file extension instead of .pl and they're usually distributed in zipped bundles that come with a .tar.gz file extension.

Some Perl modules use extensions written in the C programming language. C works at a lower level than Perl so it typically runs faster and allows module authors to do the kind of things that can't be done in Perl alone. In order to use any modules with C extensions, you'll need to have a C compiler installed on your machine. A compiler is a little like an interpreter, except that it does more work up front (i.e. when you install a module) so that it runs faster when you come to use it. Apple provide a C compiler (GCC) as part of the Xcode developer tools. You can install these from your Mac OSX installation disks, or by downloading from the Apple Developer Connection web site.

You can unpack and install Perl modules manually, but most people these days use the CPAN module to do it for them. This should already be installed on your Mac. From the Terminal command line, type sudo cpan to start it running. The sudo part of the command indicates that you want to run the cpan program as the administrator or "super user" (sudo stands for super user do). If you're not an administrator of the machine you're using then you'll have to go and find the administrator and be nice to him or her. If you are then type your password (the one you use to login to your Mac) and hit return.

The first time you run the cpan program it will ask you a bunch of questions so that it can configure itself. Answer the questions as best you can (just hit RETURN if you're not sure) and then you should be greeted with a cpan[1]> prompt.

$ sudo cpan

...a few questions later...

cpan[1]> 

Now that CPAN is configured, you can use it to install Perl modules. Let's start by installing the DateTime module. You can probably guess what this module is used for!

cpan[1]> install DateTime

...lots of output...

All tests successful.
Files=43, Tests=3277, 13 wallclock secs ( 0.51 usr  0.20 sys + 10.70 cusr  0.73 csys = 12.14 CPU)
Result: PASS
DROLSKY/DateTime-0.4501.tar.gz
/usr/bin/make test -- OK
Running make install
Prepending /Users/abw/.cpan/build/DateTime-0.4501-...blah blah blah...
Password:enter your password here

...some more output...

Appending installation info to /System/Library/Perl/5.8.8/...blah blah blah...
DROLSKY/DateTime-0.4501.tar.gz
sudo make install  -- OK

cpan[4]> 

Assuming that all the pre-installation tests pass, the CPAN module will automatically run the sudo make install command to install the module. At this point sudo will prompt you to enter your password to become the super-user. If you're not an administrator of the machine you're using then you'll have to go and find the administrator and be nice to him or her.

If the pre-installation tests don't pass then you have two choices. Either don't use the module, or install it anyway and hope for the best. It's not uncommon for modules to fail a few minor tests, particularly if the author wrote it on a different platform to yours and didn't account for minor differences in filenames, date formats, locales, or any of the other messy things that make it difficult to write portable code that works everywhere. You can force install a module if you want to use it regardless of any test failures.

cpan[2]> force install SomeDodgyModule

If you do encounter problems then please report them (or see if someone else has already reported them) at http://rt.cpan.org/.

When you're done with the CPAN module, type exit or hit Ctrl+D (i.e. hold down the Ctrl key and hit D).

Using Perl Modules

Top Close Open

Now that you've installed the DateTime module, you can use it in your Perl programs. Here's an example.

#!/usr/bin/perl

use strict;
use warnings;
use DateTime;

my $dt = DateTime->now;
print "Today is ", $dt->ymd, "\n";
print "The time is", $dt->hms, "\n";

The use DateTime; line, in case you can't figure it out for yourself, tells Perl to that you want to use the DateTime module in your program. The next line creates a DateTime object which represents the current date and time right now and stores it in a variable called $dt. The last two lines call the ymd and hms methods on the $dt object and print the values they return in nice, friendly messages. The methods return the date in year-month-date format, and the time in hours:minutes:seconds format, respectively. Save this program as before and run it from the command line. You should see output something like this (although the date and time will obviously be different):

Today is 2008-12-23
The time is 08:33:27

Some object methods accept parameters (also known as arguments) that affect the way they work. For example, the ymd and hms methods allow you to specify a different separator. Parameters are passed to the method by putting them in parentheses immediately after the method name.

print "Today is ", $dt->ymd("/"), "\n";
print "The time is", $dt->hms("."), "\n";

With the above changes, the output is now:

Today is 2008/12/23
The time is 08.33.27

Way to go, dude! You've just written your first Object-Oriented (or OO) program in Perl!

Perl Documentation

Top Close Open

Perl modules come with their own documentation, although the quality and quantity can vary wildly. The perldoc command can be used to read the documentation for a module.

$ perldoc DateTime

NAME
    DateTime − A date and time object

SYNOPSIS
    use DateTime;

    $dt = DateTime−>new( year   => 1964,
                         month  => 10,
                         day    => 16,
                         hour   => 16,
                         minute => 12,
                         second => 47,
                         nanosecond => 500000000,
                         time_zone => ’Asia/Taipei’,
                       );

    $dt = DateTime−>from_epoch( epoch => $epoch );
    $dt = DateTime−>now; # same as ( epoch => time() )

    ...etc...

You can also use perldoc to read the internal documentation for Perl.

$ perldoc perl

NAME
   perl − Practical Extraction and Report Language

SYNOPSIS
   perl [ −sTtuUWX ]      [ −hv ] [ −V[:configvar] ]
        [ −cw ] [ −d[t][:debugger] ] [ −D[number/list] ]
        [ −pna ] [ −Fpattern ] [ −l[octal] ] [ −0[octal/hexadecimal] ]
        [ −Idir ] [ −m[−]module ] [ −M[−]’module...’ ] [ −f ]
        [ −C [number/list] ]      [ −P ]      [ −S ]      [ −x[dir] ]
        [ −i[extension] ]
        [ −e ’command’ ] [ −− ] [ programfile ] [ argument ]...

   If you’re new to Perl, you should start with perlintro, which is a
   general intro for beginners and provides some background to help you
   navigate the rest of Perl’s extensive documentation.

   For ease of access, the Perl manual has been split up into several
   sections.

   Overview

       perl                Perl overview (this section)
       perlintro           Perl introduction for beginners
       perltoc             Perl documentation table of contents

    ...etc...

As the documentation explains, the Perl manual is split up into several sections. You can use perldoc to read any of the sections listed.

$ perldoc perlintro

NAME
   perlintro −− a brief introduction and overview of Perl

DESCRIPTION
   This document is intended to give you a quick overview of the Perl
   programming language, along with pointers to further documentation.

   ...etc...

You can also use perldoc to read the documentation for Perl's internal functions. You must use the -f (for function) option followed by the name of the function. For example, if you want to find out more about the split function used to split strings into smaller parts then you can type this from the command line:

$ perldoc -f split

split /PATTERN/,EXPR,LIMIT
split /PATTERN/,EXPR
split /PATTERN/
split   
      Splits the string EXPR into a list of strings and returns that
      list.  By default, empty leading fields are preserved, and
      empty trailing ones are deleted.  (If all fields are empty,
      they are considered to be trailing.)

      ...etc...

perldoc has a number of other options to help you browse around the Perl documentation. To see a full list of options, run perldoc -h for help.

$ perldoc -h

perldoc [options] PageName|ModuleName|ProgramName...
perldoc [options] -f BuiltinFunction
perldoc [options] -q FAQRegex

Options:
    -h   Display this help message
    -V   report version
    -r   Recursive search (slow)
    -i   Ignore case
    -t   Display pod using pod2text instead of pod2man and nroff
             (-t is the default on win32 unless -n is specified)
    -u     Display unformatted pod text
    -m   Display module's file in its entirety
    -n   Specify replacement for nroff

...etc...
You can also read the Perl documentation online at http://perldoc.perl.org/.

Where Next?

Top Close Open

If you haven't already read this introduction to Perl, then you should probably do that next.

If dead trees are your thing then Learning Perl is a good place to start. After that, Programming Perl is the definitive book on Perl programming. If you only own one Perl book, it should be this one.

Programming Perl is fun, but drinking beer is more fun. If you're enjoying Perl and want to learn more, or meet up with like-minded Perl folk, drink beer and discuss things Perlish, then you should seek out your local Perl Mongers group. If you haven't got a local group then either start one of your own or join London.pm because we've got members from all over the world and don't care where you live as long as you dig Perl. There's a mailing list where you can post questions about Buffy the Vampire Slayer, fine ales, ponies, or even something related to Perl. Perl is a fun programming language, and so are the people. But please enjoy them responsibly. Don't drink and code Perl. Not unless your laptop is beerproof.