Monday, December 05, 2005
Perl: File management
Perl has very robust mechanisms for dealing with file input/output. The
operators are similar to the forms of redirection you use on the command
line, including > < >> | etc. The syntax is
open(FILEHANDLE,FILENAME);
close(FILEHANDLE);
FILEHANDLEs aren't denoted a special character like $ @ %, and are not
strings, so that's one reason to quote all your strings in a program.
the FILENAME is a string, special formats are below.
open returns 1 on success, 0 on failure
Conventions for opening files
"FILE" open FILE for input also "<FILE"
"> FILE" open FILE for output, creating if necessary
">> FILE" open FILE for appending
"+> FILE" open FILE with read/write access
"| CMD" open a pipe to CMD
"CMD |" open a pipe from CMD
Note the CMD can be an arbitrary bourne shell command, including its own
pipes, redirection, etc.
Now that we have a filehandle, we need to read or write to it. The read
operator is < >, as in
# in a scalar context, read one line
$line = <FILEHANDLE>;
# in an array context, read the entire file (careful - this can take
# lots of memory!)
@lines = <FILEHANDLE>;
To print to a FILEHANDLE, print takes an optional first argument which is
the filehandle. How does it distinguish the first argument from the list
of scalars to print? (warning - loss of beauty ahead) print takes a list
as an argument (which as you'll remember is denoted by commas), so the
first argument does not have a comma.
print(FILEHANDLE "your","list","here");
--------------------------------------------------------------------------------
Example
# get ready to send the mail
if ( ! open(MAIL,"| $sendmail $recipient") ) {
&error("Could not start mail program");
}