First Steps in Perl

In this first part of a three-part series, you’ll learn the fundamentals of programming in Perl. This article is excerpted from chapter one of the book Beginning Perl, Second Edition by James Lee (Apress; ISBN: 159059391X).

Every programming language has a number of things in common. The fundamental concepts of programming are going to be the same, no matter what language in which you do them. In this chapter, we’ll investigate the things you need to know before you start writing any programs at all. For instance:

  1. What is programming anyway? What does it mean to program? 
     
  2. How do we structure programs, and make them easy to understand? 
     
  3. How do computers see numbers and letters? 
     
  4. How do we find and eliminate errors in our programs?

Of course, we’ll be looking at these from a Perl perspective, and we’ll look at a couple of basic Perl programs, and see how they’re constructed and what they do. At the end of this chapter, you will be asked to write a couple of trivial Perl programs of your own.

Programming Languages

The first question we should ask ourselves when we’re learning programming is, “What is programming?” That may sound particularly philosophical, but the answer is easy. Programming is telling a computer what you want it to do; and we do this by writing it a program. The only trick, then, is making sure that the program is written in a way the computer can understand, and to do this, we need to write it in a language that it can comprehend—a programming language, such as Perl.

There’s nothing magical about writing a program, but it does call for a particular way of thinking. When you’re telling a human what you want them to do, you take certain things for granted.

  1. The human can ask questions if they don’t understand your instructions. 
     
  2. They can break up tasks into smaller tasks by themselves. 
     
  3. They can draw parallels between the current task and a task they have completed in the past. 
     
  4. Perhaps most importantly, they can learn from demonstrations and from their ow n mistakes.

Computers can’t yet do any of these things very well—it’s still much easier to explain to someone how to tie their shoelaces than it is to set the clock on the VCR.

The most important thing you need to bear in mind, though, is that you’re never going to be able to express a task to a computer if you can’t express it to yourself. Computer programming leaves little room for vague specifications and hand waving. If you want to write a program to, say, remove useless files from your computer, you need to be able to explain how to determine whether a file is useless or not. You need to examine and break down your own mental processes when carrying out the task for yourself—do you mean a file that hasn’t been accessed for a long time? How long, precisely? Then do you delete it immediately, or do you examine it? If you examine it, how much of it? And what are you examining it for?

The first step in programming is to stop thinking in terms of “I want a program that removes useless files,” but instead think “I want a program that looks at each file on the computer in turn and deletes the file if it is over six months old, and if the first five lines do not contain any of the words ‘Simon’, ‘Perl’, or ‘Camel’”—in other words, you have to specify your task precisely.

When you’re able to do that, you need to translate that into the programming language you’re using. Unfortunately, like any human language, the programming language may not have a direct equivalent for what you’re trying to say. So, you have to get your meaning across using the parts of the language that are available to you, and this may well mean breaking down your task further. For instance, there’s no way of saying “if the first five lines do not contain any of the following words” in Perl. However, there is a way of saying “if a line contains this word,” a way of saying “get another line,” and “do this five times.” Programming is the art of putting those elements together to get them to do what you want.

So much for what you have to do—what does the computer have to do? Once we have specified the task in our programming language, the computer takes our instructions and performs them. This is called running or executing the program. Usually, we’ll specify the instructions in a file, which we edit with an ordinary text editor; sometimes, if we have got a small program, we can get away with typing the whole thing in at the command line. Either way, the instructions that we give to the computer—in this case, written in Perl—are collectively called the source code (or sometimes just source) to our program.

{mospagebreak title=Our First Perl Program}

Assuming that you now have a copy of Perl installed on your machine (perhaps having followed the instructions in the Introduction), you are ready to start using Perl. If not, go back and follow the instructions. The next step is to set up a directory for all the examples used in the rest of the book, and to write our first Perl program.

Here’s what it will look like:

#!/usr/bin/perl -w

print "Hello, world!n";

We highly suggest that you type this example in and try to make it work, so before we go any further, a quick note on editors. Perl source code is just plain text, and should be written with a plain text editor, rather than a word processor. Your operating system, whether Unix or Windows, comes with a selection of text editors. You may have a favorite already, so feel free to use it. If not, may we suggest. vi (www.vim.org), emacs (www.xemacs.org), and nedit (www.nedit.org). Windows provides WordPad and Notepad, but they lack many features of modern text editors, so they should be avoided. nedit is the most WordPad- and Notepad-like, so give it a try.

After an editor is chosen, we need to create a new directory for our work. If you are in Windows, a simple way to do this is to start up a command shell (Start ➤ Run ➤ cmd) and enter

c:> mkdir begperl
c
:> cd begperl

If you are working in any Unix variant, start a shell and enter

$ mkdir begperl
$
cd begperl

This directory will hold all the examples that we will do as we go through this book.

The next step is to fire up your editor of choice, type in the code shown previously, and save it into a file named helloworld.pl in the directory we just made. Then, to execute it, type

$ perl helloworld.pl
Hello, world!
$

Congratulations. You have successfully written and executed your first Perl program!


Note  Note that from this point on, we’ll not run through these steps again. Instead, the name we’ve given the file will be shown as a comment on the second line of the program.

You may also have noticed that the output for helloworld.pl on Windows and Unix differs in that Windows adds a blank line at the end of the output for all its Perl programs. From now on, we’ll only print the Unix output that is without the additional blank line. Windows users please be aware of this.


Let’s look at this program in detail by going through it a line at a time. The first line is

#!/usr/bin/perl -w

Normally, Perl treats a line starting with # as a comment, and ignores it. However, the # and ! characters together at the start of the first line tell Unix how the file should be run—in this case the file should be executed by the Perl interpreter, which lives in /usr/bin/perl in this example. In the Unix world, this line is known as the shebang (short for “hash bang”), and it must be located on the first line starting in the first column.


Note  Note to Unix users: your version of Perl may reside in a different location than /usr/bin/perl . Common alternative locations are /usr/local/bin/perl and /opt/bin/perl . If your version of Perl resides somewhere other than /usr/bin/perl , you will have to adjust your shebang line to point to it.

Unix users can use the invocation shown previously to execute Perl programs:

  $ perl helloworld.pl

But they can also execute Perl programs by making the file executable with the chmod command and executing it by name like this:

  $ chmod +x helloworld.pl 
  $ ./helloworld.pl


Perl also reads the shebang line regardless of whether you are on Unix, Windows, or any other system. The reason for this is to see if there are any special options it should turn on. In this case, -w is present and it instructs Perl to turn on the reporting of warnings (we’ll talk more about warnings later in this chapter).

The second line of this program is a blank line. Perl, like C, C++, and many other programming languages, treats blank lines, extra spaces, and tabs as whitespace. In Perl, whitespace can be added to the program to make it more readable.

The third line of the program is

print "Hello, world!n";

The print() function tells Perl to display the given text, without the quotation marks. The text inside the quotes is not interpreted as code, and is called a string. As we’ll see later, strings start and end with some sort of quotation mark. The n at the end of the quote is a type of escape sequence which stands for “new line.” This instructs Perl to finish the current line and take the prompt to the start of a new one.

You may be wondering why -w is so helpful. Suppose we altered our program to demon strate this, and made two mistakes by leaving out -w and modifying our code so it looks like this:

#!/usr/bin/perl

print "Hello, $world!n";

The string that we are printing now contains the text $world . As we will see in the next chapter, $world is a variable, and this variable has not been assigned a value. If we attempt to print a variable that has no value, we simply print nothing.

Save these changes in helloworld2.pl before exiting your editor. Now let’s get back to the command prompt, and type the following:

$ perl helloworld2.pl

Instead of getting the expected  

Hello, world!
$

the output would be

Hello, !
$

If we now correct one of the mistakes by including -w in our program, then helloworld2.pl looks like this:

#!/usr/bin/perl -w

print "Hello, $world!n";

Once we have saved this new change into the program, we can run it again. The output that we get now contains a warning as well as the text printed, so the screen looks like this:

$ perl helloworld2.pl
Use of uninitialized value in concatenation (.) or string at helloworld2.pl line 3. Hello, !

On the surface of things, it may seem that we have just given ourselves another line of output, but bear in mind that the first line is now a warning message, and is informing us that Perl has picked something up that may (or may not) cause problems later on in our program. Don’t worry if you don’t understand everything in the error message at the moment, just so long as you are beginning to see the usefulness of having an early warning system in place.

For Perl versions 5.6.x and higher, the -w switch can be replaced with a use warnings directive that follows after the shebang line:

#!/usr/bin/perl
use warnings;

print "Hello, world!n";

However, this code will not turn on warnings in Perl for versions pre-5.6. For backward compatibility, we will stick with the -w option.

Please check back for the next part of this series.

[gp-comments width="770" linklove="off" ]
antalya escort bayan antalya escort bayan