For example, we might want to store some information about each
bowler at Bedrock Lanes. Let's say we decide to have a series
of records, one per bowler, in which the data holds the
player's name, age, last five bowling scores, and the time and
date of his last game.
open(FRED, "<fred"); # open file fred for reading (error if file absent)
open(FRED, "+<fred"); # open file fred read/write (error if file absent)
Similarly, "+>" says to create a new file (as
">" would), but to have read access to it as
well, thus also giving read/write access:
open(WILMA, ">wilma"); # make new file wilma (wiping out existing file)
open(WILMA, "+>wilma"); # make new file wilma, but also with read access
Do you see the important difference between the two new modes? Both
give read/write access to a file. But "+<" lets
you work with an existing file; it doesn't create it. The
second mode, "+>" isn't often useful,
because it gives read/write access to a new, empty file that it has
just created. That's mostly used for temporary (scratch) files.
my $buf; # The input buffer variable
my $number_read = read(FRED, $buf, 55);
As you can see, the first parameter to read is
the filehandle. The second parameter is a buffer variable; the data
read will be placed into this variable. (Yes, this is an odd way to
get the result.) The third parameter is the number of bytes to read;
here we've asked for 55 bytes, since that's the size of
our record. Normally, you can expect the length of
$buf to be the specified number of bytes, and you
can expect that the return value (in $number_read)
to be the same. But if your current position in the file is only five
bytes from the end when you request 55 bytes, you'll get only
five. Under normal circumstances, you'll get as many bytes as
you ask for.
Once you've got those 55 bytes, what can you do with them? You
can unpack them (using the format we previously designed) to get the
bowler's name and other information, of course:
my($name, $age, $score_1, $score_2, $score_3, $score_4, $score_5, $when)
= unpack "a40 C I5 L", $buf;
print FRED pack("a40 C I5 L",
$name, $age,
$new_score, $score_1, $score_2, $score_3, $score_4,
time);
On some systems, you'll have to use seek
whenever you switch from reading to writing, even if the current
position in the file is already correct. It's not a bad idea,
then, to always use seek right before reading or
printing.