The open command opens a file for reading. Note that
STDIN, STDOUT, and STDERR are automatically opened at the start of
every Perl program, so it is not necessary to open these handles.
Besides, what file would you tell Perl to open if you did want to open
them?
The open command takes two arguments, a file handle
name and the name of the file to open.
To open a file for reading, the file name to open is
simply the name of the file to open.
Example:
# Open the unix password file for reading
open ( PASSWORD, "/etc/passwd" );
To open a file for writing, the file name to open
should include the normal Unix redirecton operator that is appropriate
for the operation you want to perform.
If you want to erase and overwrite unconditionally, use the
">" operator.
If you wish to append to whatever currently exists, use the
">>" operator.
Example:
# Open /var/results1.log for overwrite
open ( PASSWORD, ">/var/results1.log" );
# Open /var/results2.log for append
open ( PASSWORD, ">>/var/results2.log" );
Use close(FILEHANDLE) to close an open file. Note
that all filehandles are automatically closed when your program
terminates. Also, if you open a new with a previously opened
filehandle, the previous open is automatically closed. This is handy,
as most operating systems have per user limits on how many file
handles can be simultaneously opened.
Both open and close return a non-zero status if they succeeded, or
a zero status if they fail.