Home > Articles > Web Development > Perl

Introducing Perl

  • Print
  • + Share This
This chapter is from the book

This chapter is from the book

The goal in this chapter is to demonstrate many fundamental Perl features so that you may start writing Perl programs quickly. Subsequent chapters will drill more deeply into each of the topics presented here.

1.1 Getting Started

Programming languages come in all shapes and sizes. There are many ways of categorizing them. Some are considered high-level and some are considered low-level. The basic difference between these characterizations is the amount of code you need to write to express an idea. The less code you need to write, the higher the level of the language. Perl is a high-level programming language. Sometimes it is compiled and sometimes it is interpreted.

Perl was written in the early 1980s by a modern-day Renaissance man named Larry Wall. Perl combines the best features of the Unix shells, C language, and some of the more famous Unix utilities such as awk, grep, and sed. Once you are familiar with Perl, you will probably choose Perl over any of the shells, if management gives you a choice.

Perl is often referred to as a scripting language. Likewise, Perl programs are often called Perl scripts, but this distinction is largely irrelevant. Perl is currently used in a wide variety of domains, including system administration, client/server and CGI applications, text and file processing, database retrievals, biomedical processing, and many other domains.

Perl is extremely easy to learn even though there are some notational learning curves to be conquered in certain advanced features of the language.

You can download Perl freeware at the site www.activestate.com. This site has versions of Perl for most major platforms, including Windows variants, Unix variants, and Microsoft.net. For the Macintosh, you can visit www.macperl.com. For any and all information about Perl, visit www.perl.com.

Similar to other pieces of software, Perl has undergone quite a transformation since the first version was released in January 1988. Perl 2.0 was released in June 1988 and Perl 3.0 was released in October 1989. However, the most important releases are the Perl 4 release in March 1991 and the Perl 5 release in October 1994. A new version of Perl, Perl 5.6, was released in early 2001.

We will assume that you have installed Perl on your machine and that you are ready to write Perl programs.

1.1.1 The first Perl program

Here's a simple Perl program:

#     first.pl
print "Please enter your name ";
$name = <STDIN>;
chomp ($name);
print "Your name is $name";

Perl programs are written using your favorite text editor. Once you have typed your code into a file, there is no need to compile it—you simply execute it.

The # is a special character in Perl. Anything that follows this character is interpreted as a comment. A comment is terminated by the end of a line. Thus, the first four lines above are comments. (Actually, the top line is treated in a special way on Unix systems—we will see this later.)

Note that all Perl statements end in a semicolon. The print statement places data on the standard output file, the display. In this case, a prompt is displayed requesting that the user enter a name. Let's assume for now that the data that is printed needs to be wrapped in double quotes.

The next line reads a line typed by the user on the keyboard. The data will be stored inside the Perl variable $name. This data includes the newline character. In Perl, all variable names have some punctuation associated with them. The $ signifies that this variable can hold one value. This one value could be a number, a string, or something else. In any case, it will be treated as a single value. In this case, the string typed in by the user is held there. Variables that begin with $ are referred to as scalar variables. We will have more to say about these variables later.

<STDIN> is the Perl operator for reading a line from the standard input file, the keyboard. A line is defined as all of the characters up to and including the newline character. This character is generated when you press the Return (or Enter) key. Thus, the following code reads a line from the user at the keyboard:

$name = <STDIN>;

chomp is a Perl function that discards the last character in a variable only if it is a newline. Thus, the newline is discarded from $name. Finally, another print is used to print the value of the variable $name. Incidentally, there is another function, named chop, which unconditionally eliminates the last character of a variable.

Before we show how first.pl is executed, we need to make a slight diversion and mention a few differences between running your Perl scripts on a Unix system vs. running scripts on a Windows system. On Unix, the first line of every Perl script must appear as:


Unix shell programmers may recognize this. The first two characters are interpreted as special by any of the Unix shells. These two characters, #!, tell the Unix shell to use the command /usr/bin/perl to execute this script. So if you are on a Unix system, change the first line of your scripts to the complete pathname of the Perl executable, which in our case is #!/usr/bin/perl.

On Unix, after you have prepared your script, it should be made executable using the chmod command. We'll use the % as the system prompt for all of our examples:

% chmod 755 first.pl

Now you can simply execute the program as follows:

% first.pl

On a Windows machine, the easiest way to proceed is to open a DOS window and type the following to execute first.pl. On Windows, the #! line is treated as a comment.

% perl first.pl
Please enter your name Michael
Your name is Michael

Here's an example of how to execute this program on Unix:

% first.pl
Please enter your name Michael
Your name is Michael

Note that throughout the book, what the user types will be in bold letters. You can also see that all non-comment lines end with the semicolon character. Syntactically, the semi-colon is a statement separator, not a statement terminator; thus, the last statement in a script, or the last statement of any block (statements delimited by curly braces ({})), does not have to be terminated with a semicolon. However, it is good practice to place one there since you may later add some Perl code to the end of the script.

1.1.2 Some elementary I/O

Thus far, we have seen the print function used several times. We now would like to explore how a Perl program performs elementary input and output. Whenever you wish to place some information on the user's display, you use the print function. By default, your data will be sent to the standard output file, the display. Perl programs understand the concept of a filehandle, a name that is associated with a file. Perl defines a few builtin filehandles, one of which is STDOUT. If you wish, you may use a filehandle in the print function to explicitly specify the destination for the data to be printed. The following two lines are therefore functionally identical to one another:

print STDOUT "this string gets sent to the display";
print "this string gets sent to the display";

You may also create your own filehandle by using the open function. This function associates a filehandle with an actual disk file. open contains two arguments, the first of which is a filehandle and the second of which contains the name of the file to be created and the mode (input or output) of the file. The access mode is given as a punctuation symbol. The following open function associates the file named mydata with the filehandle OUTPUT. The > punctuation symbol specifies that the file will be used as an output file. Be careful here. If the file already exists, its data will be truncated.

The name OUTPUT is one of our choosing. We could have called it OUT or anything else. When you create a filehandle, use a naming convention that is mnemonically sound.

Here's a sample program, iodemo.pl, that creates a file and sends some data to the file associated with the filehandle and to the display:

#    iodemo.pl
open(OUTPUT,"> mydata");
print STDOUT "Welcome to the Perl language\n";
print OUTPUT "This data goes to a file\n";
print STDOUT "I think you will enjoy it\n";
print OUTPUT "Likewise this goes to a file also\n";

When you execute the above program, you'll only see two lines on the display. The other two lines have been sent to the file named mydata. Note that we've also placed the newline character, \n, at the end of each line. Without this character, both strings end up on the same physical output line. This is a good place to do some testing of your own. If you load a copy of iotest.pl, you may remove the newline characters, run the program again, and observe the results.

Notice that this program created a file named mydata. If you want to see the two lines in that file, you may use whichever utility comes with your system to display them (e.g., cat on Unix or type with Windows).

% iodemo.pl
Welcome to the Perl language
I think you will enjoy it
% display mydata
This data goes to a file
Likewise this goes to a file also

The next example will demonstrate how to open a file for input. Ultimately, we will also need to know how to handle errors produced by open, but we will delay that until later.

You may open a file for input simply by using the < symbol at the beginning of the second argument to the open function. Of course, the file should exist or an attempt to open it will cause an error. If you do not specify any punctuation with the second argument, then the file is opened for input by default. Thus, the following lines are equivalent:

open(INPUT, "< input");
open(INPUT, "input");

Now that you have created the association between the filehandle and an actual disk file, you may use the <> operator to read from the file.

$line = <INPUT>;

$line is a scalar variable used to store the line that is entered by the user. We saw something close to this earlier when we read a line from the standard input with:

$line = <STDIN>;

The difference between the previous two lines of code is that INPUT is a filehandle created in the Perl program, whereas STDIN is a filehandle predefined in the Perl language. The snippet of code below reads the only two lines from the file mydata created above and sends them to the display:

open(INPUTFILE, "< mydata");
$firstline = <INPUTFILE>;
print "$firstline";
$firstline = <INPUTFILE>;
print "$firstline";

Each line of the form:

$variable = <SOME_FILE_HANDLE>;

reads the next line from the file associated with:


There's also a predefined filehandle, named ARGV, which is used to step through a group of files named on the command line. We will see more information about this and other filehandles later.

  • + Share This
  • 🔖 Save To Your Account