Pipes | Streams  «Prev  Next»

Lesson 3Writing to file streams
ObjectiveWrite to a file stream.

Writing to File Streams in Perl

File streams are the most common use of streams. They are used for most of the normal input/output work you will do with files in Perl.

Writing files

As an example of how to open and write to a file in Perl, consider this simple program which logs referers from a Web page:

#!/usr/bin/perl

# use a logdir that you know the Web server
# has permission to create a file in
$logdir = "/home/billw/var/logs";
$logfile = "test-referer.log";
$reflog = "$logdir/$logfile";

$crlf = "\x0d\x0a";
print "content-type: text/html$crlf";
print "$crlf";

$referer = $ENV{HTTP_REFERER} or exit 0;

print qq(<a href="$referer">Back</a>);

lock();
open(REFLOG, ">>$reflog") or die "cannot open $reflog!\n";
print REFLOG "$referer\n";
close REFLOG;
unlock();


lock() and unlock() functions

The lock() and unlock() functions are the same that we have been using throughout this course.
The environment variable, HTTP_REFERER comes from the browser (remember, all the HTTP_anything variables come from the browser) when the browser was referred to your page by a hyperlink on another page. So you will only get a log entry here when your page is hit from a link on another page, and that browser sends the Referer: header.
Notice that the referer log must be created in a directory in which the Web server has permissions to create files. This is because CGI programs are run by a Web server, and a Web server typically runs as a user with very few permissions (in Unix, this is usually a user called "nobody").

The
open(REFLOG, ">>$reflog")
expression opens the file with the path contained in the $reflog variable.
If the file already exists, it is appended to, otherwise the file is created. The REFLOG token is used as a handle for the stream. In Perlese it's called a filehandle. The print() function is used to write to the file by specifying the filehandle before the actual data that is to be written. There is no comma because this is how perl knows that the filehandle is not another parameter to be printed.
This program is most useful if it is executed as a server-side Include. I use a similar version on my CGI book page, with a command like this in the HTML:
<!--#exec cgi="reflog.cgi" -->

Open Write To File - Exercise

Click the Exercise link below to open and write to a file.
Open Write To File - Exercise