Click to See Complete Forum and Search --> : Having trouble truncating a datafile...


Stavrogin
01-24-2004, 04:43 PM
Here's my script:

#!/usr/bin/perl

$data_file = '/Library/Webserver/CGI-Executables/data/datafile.txt';
$newline = <<"walnuts";
//insertcomment//
Here is the new line.
walnuts

#open non-destructively, feed entries into a string
sysopen(ENTRIES, "$data_file", O_RDWR) or die "can't open $data_file: $!";
flock(ENTRIES, 2) or die "can't LOCK_EX $data_file: $!";
while (<ENTRIES>) {
$all_entries .= $_;
}
$_ =~ s/insertcomment/$newline/;
$_ = $newdatafile;

seek(ENTRIES, 0, 0) or die "can't rewind $data_file: $!";
truncate(ENTRIES, 0) or die "can't truncate $data_file: $!";
print ENTRIES $newdatafile or die "can't print to $data_file: $!";
close(ENTRIES) or die "can't close $data_file: $!";

I get an error message when I run this from the command line: can't truncate /Library/Webserver/CGI-Executables/data/datafile.txt: Invalid argument at ./writeto.cgi line 19, <ENTRIES> line 6.

How can I fix this?

next1
01-25-2004, 10:35 AM
can't really tell what is wrong from the info you've posted here, but i can suggest a quicker and easier way of doing what you're doing that should work fine for you.

try using File::Slurp, handy module.

then you can just say something like:

$data = read_file($file);
$data =~ s/<thing>/$new_thing/;
write_file($file, $data);

done!