Thư viện tri thức trực tuyến
Kho tài liệu với 50,000+ tài liệu học thuật
© 2023 Siêu thị PDF - Kho tài liệu học thuật hàng đầu Việt Nam

Minimal Perl For UNIX and Linux People 2 doc
Nội dung xem thử
Mô tả chi tiết
WRITING ONE-LINE PROGRAMS 13
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 program 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.
14 CHAPTER 1 INTRODUCING MINIMAL PERL
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 processing 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 SUMMARY
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 invocation options to duplicate the input-processing behavior of Unix filter programs.
SUMMARY 15
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 invocation options 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. Learning about them will give you a better understanding of the inner workings of the simple programs you’ve seen thus far and will prepare you for the many useful and
interesting programs coming up in subsequent chapters.
16
CHAPTER 2
Perl essentials
2.1 Perl’s invocation options 17
2.2 Using variables 23
2.3 Loading modules: -M 27
2.4 Writing simple scripts 29
2.5 Additional special variables 42
2.6 Standard option clusters 44
2.7 Constructing programs 47
2.8 Summary 51
This chapter introduces the most essential features of Perl, to pave your way for the
programming examples you’ll see in the following chapters. Among the topics we’ll
cover here are the use of Perl’s special variables, how to write Perl one-line commands
and scripts, and the fundamentals of using Perl modules.
But we don’t discuss everything you need to know about Perl in this chapter. Further details on this chapter’s topics—and more specialized ones not discussed here—
are presented in later chapters, in the context of illustrative programming examples.
Some of the language features discussed here won’t be used until part 2 of the book,
so it’s not necessary for you to read this chapter in its entirety right now. If you haven’t
learned a computer programming language before—or if you have, but you’re eager
to get started with Perl—you should read the most important sections1 now (2.1,
2.4.5, 2.5.1, and 2.6, including subsections) and then proceed to the next chapter.
This chapter will serve you well as a reference document, so you should revisit it
when you need to brush up on any of its topics. To make this easy for you, when
“essential” features are used in programs in the following chapters, cross-references
will refer you back to the relevant sections in this chapter. Forward references are also
1 To help you spot them, the headings for these sections are marked with the symbol.