Filehandles
Unless you’re using artificial intelligence to model a solipsistic
philosopher, your program needs some way to communicate with the outside
world. In lines 4 and 8 of our Average Example you’ll see the word
GRADES, which exemplifies another of
Perl’s data types, the filehandle. A filehandle is just a name you give to a file, device, socket, or pipe to
help you remember which one you’re talking about, and to hide some of the
complexities of buffering and such. (Internally, filehandles are similar
to streams from a language like C++ or I/O channels from BASIC.)
Filehandles make it easier for you to get input from and send output to many different places. Part of what makes Perl a good glue language is that it can talk to many files and processes at once. Having nice symbolic names for various external objects is just part of being a good glue language.[22]
You create a filehandle and attach it to a file by using open. The open function takes at least two parameters: the filehandle and filename
you want to associate it with. Perl also gives you some predefined (and
preopened) filehandles. STDIN
is your program’s normal input channel, while STDOUT is your program’s
normal output channel. And STDERR is
an additional output channel that allows your program to
make snide remarks off to the side while it transforms (or attempts to
transform) your input into your output.[23] In lines 4 and 5 of our program, we also tell our new
GRADES filehandle and the existing
STDOUT filehandle ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access