PerlTutor - The Interactive Perl Tutorial

Lesson 1 - Getting Started

In order to benefit from this course, you will need a computer with Perl 5 installed. As you read the examples, you will want to try them. To see if your system already has Perl installed, go to a command-line prompt and type:

perl -v

Hopefully, the response will be something like this:

This is perl, version 5.005_03 built for PA-RISC1.1

Copyright 1987-1999, 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.0 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.com/, the Perl Home Page.

The exact wording will vary depending on your operating system and version of Perl. If you get an error message, or you have version 4 of Perl, you will need to see your system administrator or install Perl yourself. Don't worry if your version of Perl 5 isn't the very latest release - for the purpose of this course, it won't matter. If you have Perl 5 available, skip to Section 1.2.

1.1 Getting and Installing Perl

Perl is Open Source software. You can download it for free as source code or as a pre-compiled binary distribution. Full instructions on downloading and installing Perl can be found in a dedicated area of the Perl Home Page at:

http://www.perl.com/pub/language/info/software.html

If your host computer is a PC running Windows or NT, an alternative is to download the ActivePerl distribution:

http://www.activestate.com/ActivePerl/

The download and installation process is more than adequately described on these sites, and is not reproduced here. Having installed Perl, you are ready to try your first Perl program!

1.2 Perl meets Hello World

If you are familiar with other programming languages, you will know that the first program you write in any language is invariably a one-liner which prints on your screen:

Hello, World!

To avoid breaking this sacred (albeit eccentric) tradition, here is one way to write the program in Perl:

#!/usr/local/bin/perl
print ("Hello, World\n");

To get this working, the steps involved are:

  • Create a text file to hold the Perl program.
  • Run the perl program file.

Any text editor can be used to create and save the file - e.g. 'vi' on Unix systems, 'Notepad' on Windows/NT systems.

The first line is a special instruction which says 'this is a Perl program'. It is known as the 'shebang' (hash-bang) line, and tells your computer how to execute the file. Under Unix, this makes sense. Under PC/Win32 systems, the system must already know how to execute the file before it is loaded so the line is not strictly needed. However, the line is not completely ignored, as it is searched for any switches you may have given Perl (for example -w to turn on warnings). It is common practice to always include a 'shebang' line at the start of a Perl program - the content will vary depending on the location of the Perl interpreter on your system. If you are using a PC/Win32 system, it might be something like c:\perl5\bin\perl.

Find out where Perl is installed on your system, and use that path in the first line of all your Perl programs.

The second line is the complete executable part of the program. It consists of one statement - the keyword print plus a single argument which is a string containing 'Hello, World'. The second line is terminated with a semicolon. More details on the above terms later - for now, what you need to do is:

  • type the program using your favourite text editor
  • save it to a file named hello.pl
  • (On Unix systems ONLY) type chmod +x hello.pl - make the file executable
  • run (execute) the program by typing perl hello.pl or hello.pl

When you run the program, the Perl interpreter parses the program and then executes the compiled form. The file has only one executable line, which prints a message to the screen. You should see the line:

Hello, World!

If you get an error message something like this:

/usr/bin/sh: ./hello.pl: not found

then your first line is probably not pointing to the right location for the perl interpreter on your system. If you get a message like :

Can't open perl script "hello.pl": No such file or directory

then Perl is definitely installed, but you have either got the name of the script wrong or the script is not in the same directory as where you are trying to run it from. For example, maybe you saved in script in c:\windows and you are in c:\perl\scripts - so of course Perl complains it can't find the script.

Once you get the program working, give yourself a pat on the back. You now have the basic tools at your disposal for completing the PerlTutor course!

1.3 The Anatomy of a Perl Program

A Perl program consists of a text file containing a series of Perl statements. The broad syntactic rules governing the layout of Perl programs are:

  • Leading spaces on a line are ignored.
  • You can start a Perl statement at the beginning of the line, or indented for clarity (recommended)
  • Statements are terminated with a semicolon.
  • Spaces, tabs, and blank lines outside of strings are irrelevant.
  • Statements may be split over several lines for clarity.
  • Anything after a hash sign (#) is ignored, except in strings. The # denotes the start of a comment.
  • A string is basically a series of characters enclosed in quotes (Lesson 2 deals with strings in detail)

Here is a trivial example to illustrate some of these features

#!/usr/local/bin/perl 
# This is a simple program to print 'Perl Programming is Great Funl'
#
print ("Perl Programming"); # Note that statements must be terminated with a semicolon
    print ("is"); # This line is indented
    print
  
    ("Great Fun\n"); # This statement is split over 2 lines - note that the 1st line does not have a semicolon

Comments are used to document your program, and are ignored by Perl. The \n in the last line is a special character sequence which means 'Print a newline'. This and other 'backslash character sequences' are covered in detail by Lesson 02.

There is of course a much neater way to write this program, which is print ("Perl Programming is Great Fun\n"); This leads nicely onto one of the key themes or 'anthems' of perl, which is 'There's More Than One Way To Do It'. This is sometimes shortened to TMTOWTDI (pronounced tim-toady). People approach tasks in very different ways, and sometimes come out with very different solutions to the same problem. Perl is accomodating - it doesn't force any particular style on you. As you work through the PerlTutor lessons, you should become increasingly aware of this.

1.4 Behind the Scenes

So what actually happens between you typing perl hello.pl and the message Hello, World! being displayed? In a nutshell:

  • The perl interpreter reads your file from disk
  • The perl interpreter parses and compiles the program
  • The perl interpreter executes your program

If your program contains syntax errors, they are displayed at the parsing stage, and the execution is aborted. This means that you will never get a syntax error from the program during execution. Also, the whitespace and comments have disappeared by execution time, and so won't slow your program down.

Perl sits in between traditional scripting or interpreted languages - such as Unix shell scripts - and traditional compiled languages - such as C++, where an inital compile stage produces object code files which are executed. In some ways Perl gets the best of both worlds:

  • It's an interpreter because there are no object code files lying around filling up your disk
  • It's a compiler because the program is comletely parsed before the first statement is read.

For this reason, you will see the terms 'Perl script' and 'Perl program' used interchangeably. As far as Perl is concerned, a script and a program are the same animal.

Check Point
Which two character sequence normally starts the 1st line of a Perl program?


Which character is used to terminate Perl statements?
A Perl statement must not be split into more than one line: True   False
Which character denotes the start of a comment?

Syntax errors detected during program execution will cause execution to abort: True   False

 

Exercises

1. Write a Perl program which prints on the screen the three lines:

This parrot is no more!
He has ceased to be!
E's expired and gone to meet 'is maker!

(Hint - don't forget the \n (newline) character). Type the program in, and get it to run. Press the Sample Answer button to compare your answer.

(grateful thanks to Mr. M. Python for help in preparing this exercise...)

«previous page
next page»
Copyright (c) Sharp Software  - Reproduction of PerlTutor in any format is strictly prohibited