• Aucun résultat trouvé

W RITING ONE - LINE PROGRAMS

Dans le document Minimal Perl (Page 44-49)

Introducing Minimal Perl

1.6 W RITING ONE - LINE PROGRAMS

There are two ways to write Perl programs. With the script approach, the program is placed in a file that starts with a perl shebang line, such as #! /usr/bin/perl. With the command approach, a perl command is typed interactively to the Shell, consisting of a short program preceded by the e invocation option (see the following example).6

That e option (for execution of programs) is the foundation on which Perl one-liners (one-line commands) are built, because it provides a convenient way for highly compact programs to be conveyed to perl without the overhead of creating a script file.

Here’s an example of a simple yet useful program that can be written as a one-line command:

$ perl -wl -e 'print 22/7;' # Gimme pi!

3.14285714285714

$

The print function is the general facility for sending results to the current output destination, which is the user’s terminal by default. It’s followed, in this case, by an expression describing the division of two numbers, positioned in the argument list of print. Accordingly, the result of that calculation gets printed.

Just as the pattern argument to a grep command would be single-quoted to prevent the Shell from tampering with its contents (e.g., grep '* On Sale! *' adverts), the Perl program is also enclosed in single quotes.

The w option enables warnings, which are especially helpful for new programmers.

The l option (the lowercase L) requests automatic line-end processing, which in this case ensures that a Unix-appropriate record separator is printed after the numerical result. That allows the next Shell prompt to appear on a fresh line, as expected. These two options are so beneficial that they’re used with almost every program in this book, and they deserve to be used routinely by you as well.

Now you know how to type a simple Perl program directly to the Shell and have its output delivered to the screen. But many programs must collect and process input

6 Further details on creating Perl commands and scripts are provided in sections 2.1 and 2.4.

in addition to generating output, and doing so requires the use of additional Perl invocation options. We’ll cover them in chapter 2.

Next, we’ll consider the benefits of striving for simplicity in Perl programming, and an important philosophical principle underlying Minimal Perl.

1.6.1 Balancing simplicity and readability

You’ll soon see how the essential behavior of the Unix cat command can be replicated in Perl using various techniques. Along the way you’ll learn how to write an elementary filter program, which will serve as the foundation for dozens of more interesting ones that are covered later in this book. During this discussion, the Minimal Perl philoso-phy of employing the simplest practical solution from the rich collection of alterna-tives will be demonstrated.

Filter programs—such as the grep, sed, and sort commands of Unix—take input, process it in some way, and then emit the results. The single Perl feature that’s most valuable for writing filters is the implicit loop of the n invocation option, which makes it easy to process lines one at a time. It’s much Lazier (and wiser) to use this option than to continually reinvent the wheels of its infrastructure on your own (as squared JAPHs are inclined to do).

One of the more important lessons conveyed in the following sections is that although “There’s More Than One Way To Do It” in Perl, those ways aren’t all equal—some are preferable to others, based on their optimal balance of simplicity and readability.

You’ll see some well-crafted programs in the following section, as well as alterna-tives that are either too large and complex, or too succinct and cryptic. Keep in mind that you won’t need to absorb the Perl techniques that are demonstrated in passing at this time, because they’ll be covered in detail later. And please note that the complex programs are presented primarily for their shock value—they won’t be on the test!

TIP Using Perl’s n option makes it easy to write tiny but powerful filter programs.

1.6.2 Implementing simple filters

Our exploration of filtering with Perl begins with a consideration of the Unix cat command and a replication of its basic functionality in Perl. Behold the syntax of the humble cat, which is typical of Unix filter programs:

cat file file2

This invocation causes cat to open file, read a line, write that line to the screen, and repeat those steps until all lines have been processed. Then it does the same for file2.

For example:

$ cat exotic_fruits exotic_jerkies fig

kiwi camel python

Now we’ll examine some Perl programs that act as cat-like filters. Why? Because the simplicity of cat—called a null filter, since it doesn’t change its input—makes it an ideal starting point for our explorations of Perl’s data-processing facilities.

Here’s an example of the hard way to emulate cat with Perl, using a script that takes an unnecessarily complex approach:

#! /usr/bin/perl -wl

@ARGV or @ARGV = '-';

foreach my $file (@ARGV) { open IN, "< $file" or

die "$0: Open of $file failed, code $!\n";

while ( defined ($_=<IN>) ) { print $_;

}

close IN or

die "$0: Close of $file failed, code $!\n";

}

Only masochists, paranoiacs, or programmers abused in their early years by the C language (e.g., squared JAPHs) would write a Perl program this way.7 That’s because Perl provides facilities to automatically create the filtering infrastructure for you—all you have to do is ask for it!

An equivalent yet considerably simpler approach is shown next. In this case, Perl’s input operator (<>) is used to automatically acquire data from filename arguments or STDIN (as detailed in chapter 10). Unlike the previous solution, this cat-like pro-gram is small enough to implement as a one-liner:

perl -wl -e 'while (<>) { print; }' file file2

But even this is too much coding! You’re busy, and typing is tiresome, error-prone, and likely to give you carpal tunnel syndrome, so you should try to minimize it (within reason). Accordingly, the ideal solution to writing a basic filter program in Perl is the following, which uses the n option:

perl -wnl -e 'print;' file file2 # OPTIMALLY simple!

The beauty of this version is that it lets you focus on the filtering being implemented in the program, which in this case is no filtering at all—the program just prints every

7 There are cases where it makes sense to write your own loops in Perl, as shown in chapter 10, but this isn’t one of them.

line it reads. That’s easy to see when you aren’t distracted by a dozen lines of boilerplate input-reading code, as you were with the scripted equivalent shown earlier.

Where did the while loop go? It’s still there, but it’s invisible, because the n option tells Perl, “Insert the usual input-reading loop for this Lazy programmer, with no automatic printing of the input lines.”

A fuller explanation of how the n option works is given in chapter 10. For the time being, just remember that it lets you forget about the mundane details of input pro-cessing so you can concentrate on the task at hand.

Believe it or not, there’s a way to write a cat-like program in Perl that involves even less typing:

perl -wpl -e '' file file2 # OVERLY simple!

By now, you’re probably thinking that Perl’s reputation in some circles as a write-only language (i.e., one nobody can read) may be well deserved. That’s understandable, and we’ll return to this matter in a moment. But first, let’s discuss how this program works—which certainly isn’t obvious.

The p option requests the usual input-reading loop, but with automatic printing of each input line after it has been processed. In this case, no processing is specified, because there’s no program between those quotes. Yet it still works, because the p option provides the essential cat-like behavior of printing each input line.

This bizarrely cryptic solution is, frankly, a case of taking a good thing too far. It’s the kind of coding that may lead IT managers to wonder whether Larry has a screw loose somewhere—and to hope their competitors will hire as many Perl programmers as they can find.

Of course, it’s unwise to drive your colleagues crazy, and tarnish your reputation, by writing programs that appear to be grossly defective—even if they work! For this reason, the optimally simple form shown previously with the n option and the explicit print statement is the approach used for most filter programs in Minimal Perl.

1.7 S

UMMARY

As illustrated by the Traveler’s tale at the beginning of this chapter, and the cat-like filter programs we examined later, the Perl programmer often has the choice of writing a complex or a simple program to handle a particular task. You can use this flexibility to create programs that range from minor masterpieces of inscrutability—because they’re so tiny and mysterious—to major masterpieces of verbosity—because they’re so voluminous and long-winded. The Perl subset I call Minimal Perl avoids programs at both ends of that spectrum, because they can’t be readily understood or maintained, and there are always concise yet readable alternatives that are more prudent choices.

To make Perl easier for Unix people to learn, Minimal Perl favors simple and compact approaches based on familiar features of Unix, including the use of invoca-tion opinvoca-tions to duplicate the input-processing behavior of Unix filter programs.

Minimal Perl exploits the power of Perl to indulge the programmer’s Laziness, which allows energy to be redirected from the mundane aspects of programming toward more productive uses of its capabilities. For instance, the n and p invoca-tion opinvoca-tions allow Lazy Perl programmers—those who strive to work efficiently—to avoid retyping the generic input-reading loop in every filter program they write for the rest of their Perl programming careers. As an additional benefit, using these options also lets them write many useful programs as one-line commands rather than as larger scripts.

In the next chapter, we’ll discuss several of Perl’s other invocation options. Learn-ing about them will give you a better understandLearn-ing of the inner workLearn-ings of the sim-ple programs you’ve seen thus far and will prepare you for the many useful and interesting programs coming up in subsequent chapters.

C H A P T E R 2

Dans le document Minimal Perl (Page 44-49)