Home Index

Start with Perl CGI now! Part III - Files and File Operations
 
Date: June  01 2001
Subject: Online Programmer Ezine, Volume 2, No.5
Article: 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
and Pascal.

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 
itself.

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";

or

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.

open(INFILE,"settings.txt");

Above command opens a file for reading. If you want to 
open a file for other purpose you must add below symbols
to filename.

> 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.


#!/usr/bin/perl

print "Content-type: text/html\n\n";
print "File Write Example";

open(OUTFILE,">1.txt");

print OUTFILE "Hello world!";

close OUTFILE


If you have any question about Perl and cgi programming you 
can ask it in our programming forums.

http://op.htmsoft.com/forums



Home Index
© 2001 OnlineProgrammer (HtmSoft.com) . All Rights Reserved