Perl CGI: The Happy Path File Input and Output
Prepared by Bill Kilgallon,
Bill@KilgallonFamily.com
- To either read or write a file in Perl, you must first open it.
- When you open the file, you must give it a unique filehandle.
This is just a name you use later to reference that file. This allows
multiple files to be open at the same time without confusion. Well,
at least Perl won't be confused, the rest of us probably
will.
- To specify a file is to be opened for reading, add the "<"
character to the start of the filename. The command to open a file
named "counter.txt" for reading would be "open (INPUTFILE,
"<counter.txt");". The name "INPUTFILE" could be anything, but
it is traditionally all caps and should be descriptive.
- To read from a file opened for reading with the above command,
you use the diamond operator ("<FILEHANDLE>") and put the result in
a scalar. For example, to read a single line from a file opened with
the above command, you would use " my $counter =
<INPUTFILE>;". When executed, the shoebox named "$counter"
will contain the first line from the file counter.txt.
- Any file opened should be closed. Use the "close(FILEHANDLE)"
directive. For example, given the above open, the correct close
command would be " close(INPUTFILE); "
- To specify a file should be opened for writing, and that it
should be erased and started empty regardless of it's current
contents, put the ">" character at the beginning of the name. For
example, to open the file "counter.txt" for writing (and truncating),
you would use the command " open(OUTFILE, ">counter.txt");".
- To output data to this file, you give the "print" command an
argument of your file handle. For example to write to the file opened
above, you would use the command " print OUTFILE "Hello
World\n";"
Return to Index