Полезная информация

Learning Perl on Win32 Systems

Learning Perl on Win32 SystemsSearch this book
Previous: 10.1 What Is a Filehandle?Chapter 10
Filehandles and File Tests
Next: 10.3 Using Pathnames and Filenames
 

10.2 Opening and Closing a Filehandle

Perl provides three filehandles - STDIN, STDOUT, and STDERR - which are automatically open to files or devices established by the program's parent process (probably a command console). You use the open function to open additional filehandles. The syntax looks like this:

open(FILEHANDLE,"somename");

where FILEHANDLE is the new filehandle and somename is the external filename (such as a file or a device) that will be associated with the new filehandle. This invocation opens the filehandle for reading. To open a file for writing, use the same open function, but prefix the filename with a greater-than sign (as with redirection in cmd.exe or command.com):

open(OUT, ">outfile");

We'll see in a later section, "Using Filehandles," how to use this filehandle. Also, as at the command prompt, you can open a file for appending by using two greater-than signs for a prefix, as shown:

open(LOGFILE, ">>mylogfile");

All forms of open return true for success and false for failure. (Opening a file for input fails, for example, if the file is not there or cannot be accessed because of permissions; opening a file for output fails if the file is write protected, or if the directory is not writable or accessible.)

When you are finished with a filehandle, you can close it with the close operator, like so:

close(LOGFILE);

Reopening a filehandle also closes the previously opened file automatically, as does exiting the program. Because of this feature, many Perl programs don't bother with close. But the function is there if you want to be tidy or make sure that all of the data is flushed out before program termination. A close call could also fail if the disk filled up, the remote server that held the file became inaccessible, or any of various other esoteric problems occurred. You should always check the return values of all system calls.


Previous: 10.1 What Is a Filehandle?Learning Perl on Win32 SystemsNext: 10.3 Using Pathnames and Filenames
10.1 What Is a Filehandle?Book Index10.3 Using Pathnames and Filenames