Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Writing and modifying a file.

Status
Not open for further replies.

atom267

Technical User
Mar 3, 2004
5
0
0
GB
Hello I'm discovering perl and cgi scripts. I'm trying to modify the content of a file i've written in. The problem is that i can't position the pointer to the beginning of the file. I've been trying to use seek(OUTF,0,0); but it does not work. So my question is: is there a possibility to modify the content of a file, without having to create a temporary file.
This is the piece of code i'm trying to make working.

seek(OUTF,0,0);

@data = <INF>;
if (@data[0]<1)
{
print OUTF "1\n";
}
else
{
$var=1+@data[0];
print OUTF "$var\n";
seek(OUTF,0,2);
}
print OUTF "$FORM{'name'}|$FORM{'description'}|$FORM{'price'}|$FORM{'supplier'}|$FORM{'stock'}\n";
close(OUTF);

Basically, i want to insert a number in the first line of the file who will indicate the number of lines in the file. Every time a new record is inserted, this number is incremented. I just need to know how i can write at the beginning of the file.

Thanks

Thomas
 
You might want to try the Tie::File module for this.. basically, it lets you treat the file as an array and any changes you make to the array are automatically changed in the file. It doesn't load the entire file into memory, so it's good for working with large files.


this will change the first line of the file to "1"
Code:
use Tie::File;

tie @array, 'Tie::File', "file.txt" or die $!;
$array[0] = 1;
 
In my experience it takes longer to do the tie/modify than to just read through the file writing to a new one then move the file :

open(FILE,$file);
open(OUT,">$file.out");
print OUT "prepend\n";
while(<FILE>) {print OUT}
close(OUT);
close(FILE);
`mv $file.out $file`;


UNLESS you are just changing 1 byte for another...then it'll be fast to do the tie...if you are inserting a line or inserting more bytes it'll have to go all the way through..



(ps...use error checking etc before doing the move...dont want to accidentially destroy the file ..like if the disk fills up and it cant finish the write...)
 
Thanks to both of you. I'l try both of these solutions and choose the more easy to use :)
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top