On Sun, Jul 18, 2004 at 08:39:09PM -0500, Rod Adams wrote:
> Case 1:
> So I wanted to do a read/write scan, so I create my TextFile, start
> reading in data, so the file is opened for reading. Then, I come to the
> part where I want to update something, so I do a write command. Suddenly
> the file has to be closed, and then re-opened for read and write. And
> all my buffers, file pointers and the like are reset, (though curable
> with very careful planning), leaving me in a bad spot. Better if I could
> just declare the file open for read and write at open time.
>
> Case 2:
> I meant to use some critical data file in read-only mode, and accidently
> use a write command somewhere I didn't mean to, and silently just
> clobbered /etc/passwd. Better if I could have just opened the file read
> only, and trigger an error on the write command.
>
> What design philosophy would you envision TextFile taking to handle both
> these cases in a coherent fashion?
my $default is TextFile("/tmp/foo");
my $rw is TextFile("/tmp/foo") is rw;
my $ro is TextFile("/etc/passwd") is const;
$default will have the semantics that Dave has been
describing--initially opened read-only, then re-opened as r/w if you
write to it.
$rw is explicitly r/w. Attempts to write to it succeed, and do not
require an implicit re-open.
$ro is explicitly ro. Attempts to write to it fail, and do not
perform an implicit re-open.
Given the above code, here is some usage:
print $ro.readline(); # Prints first line
$ro = "boom!"; # THROWS AN ERROR
(assume error was trapped somehow)
# Print file, inefficiently
print $default.readline for 1..$default.lines;
# Append a line
$rw .= "an additional line\n";
# New line is visible through $rw
print $rw.lines[-1]; # (*)
# last line not yet visible through $default because it was
# added by external handle--just like in a tail -f, we
# need to move file pointer manually
$default.seek(File.current_pos);
# Can't re-open for write mode, since another handle
# already has the write-lock. Throw error to that effect.
$default = "oops, this doesn't work";
(*) The .lines[-1] semantic is feasible if we are willing to tolerate
very slow performance (at least the first time; it could cache the
locations of $/ after scanning and dump the cache if $/ changes), the
fact that it wouldn't work on all files (/dev/null, /dev/zero, etc),
and a few other issues.
> I don't think anyone (read: Larry) has declared exactly what the
> capabilities of the default file handle object are yet. It seems me that
> you could very well get what you want.
True on both counts.
--Dks