Opening a Filehandle
So you’ve seen that Perl provides three filehandles—STDIN
, STDOUT
, and STDERR
—which are automatically open to files
or devices established by the program’s parent process (probably the
shell). When you need other filehandles, use the open
operator to tell Perl to ask the
operating system to open the connection between your program and the
outside world. Here are some examples:
open CONFIG, "dino"; open CONFIG, "<dino"; open BEDROCK, ">fred"; open LOG, ">>logfile";
The first one opens a filehandle called CONFIG
to a file called dino. That is, the (existing) file dino will be opened and whatever it holds
will come into our program through the filehandle named CONFIG
. This is similar to the way that data from a file could
come in through STDIN
if the command
line had a shell redirection like <dino
. In fact, the second example uses
exactly that sequence. The second does the same as the first, but the
less-than sign explicitly says “use this filename for input,” even
though that’s the default.[*]
Although you don’t have to use the less-than sign to open a file
for input, we include that because, as you can see in the third example,
a greater-than sign means to create a new file for output.
This opens the filehandle BEDROCK
for
output to the new file fred. Just
as when the greater-than sign is used in shell redirection, we’re
sending the output to a new file called fred. If there’s already a file of that name, we’re asking to wipe it out and replace it with this new ...
Get Learning Perl, 5th Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.