01, 2001 |
Programmer Ezine, Volume 2, No.5 |
Start with Perl CGI now! Part III - Files and File Operations |
|If you have been a programmer for a while you will|
admit that file operations are one of the most important
capabilities of every programming language.
In this issue of perl cgi programming we will study
file operations in perl language. In next issue we will
first see more examples about file operations and then we
will start working on perl CGI programs.
Working with files in perl language is very similar to C
In perl we use a particular variable called "File Handle"
to access file operations on a file.
In fact we will associate a variable called a 'file handle'
to a filename. After this every time we want to access the
file we will refer to file handle instead of filename
We have also some predefined files handles (the same as C)
STDIN, STDOUT and STDERR.
STDIN is standard input. We use this handle to read
keyboard or data sent by a web browser as a standard file.
STDOUT is standard output. This is used to write to console
or web browser in web applications.
STDERR is standard error. This one is used to send error
messages to console. In web applications it is used to write
error message to server error log file.
Writing to STDOUT and STDERR is very easy. You can use
"print" command to send output to "STDOUT" and "STDERR".
print STDOUT "Hello world.\n";
print (STDOUT "Hello world.\n");
Pay attention that no comma separates parentheses.
We can use above methods for real files too.
The only difference is that we must open a file before
we can use it and we must close it after using.
We can choose any name for our file handle but it is
usual to type it in uppercase.
Above command opens a file for reading. If you want to
open a file for other purpose you must add below symbols
> open file for reading,
(this is default and you can omit it)
< open file for writing
>> open file for append
+< open file for read/write
| (before filename) is used when we want to pipe a
text to something such as a shell command
| (after filename) is used when we want to pipe
something to our perl program.
In this section we will see a simple example. In next issue
we will have an example for each of these options.
print "Content-type: text/html\n\n";
print "File Write Example";
print OUTFILE "Hello world!";
If you have any question about Perl and cgi programming you
can ask it in our programming forums.