http://qs321.pair.com?node_id=20308

Kozz has asked for the wisdom of the Perl Monks concerning the following question:

Most wise monks:

I'm having some difficulties. I want to open a file for read/write and immediately obtain an exclusive lock, read the whole thing into a scalar (or array), do something with the data I read, then write it all back to the file (clobbering whatever was once there), then close it. But how do I do all this? I thought I saw a good explanation in a post a week ago, but I couldn't find the post. And I also tried reading the manpages, but was unable to decipher all the functions. Perhaps I'm missing something.
Here's what I've got:
open(FH, "+< filename.txt") || die "$!"; #open the file for read/writ +e flock(FH, LOCK_EX); # get an exclusive lock seek(FH, 0, SEEK_SET); # move filepointer to beginning of file read(FH, $scalar, $bytes); # what if I want the whole thing, no matter + how many bytes? # do something with # $scalar here seek(FH, 0, SEEK_SET); # move filepointer to beginning of file (is + this correct syntax for this?) print FH $scalar; # print at beginning of file, clobbering ol +d data truncate(FH, tell(FH)); # truncate any data beyond where we've writ +ten (is this correct as well?) close(FH); # close the file
So the problem is that this seems to leave me with an empty file, rather than reading and then writing what I had. Perhaps I'm intermixing some seek/read/truncate calls incorrectly or something. In addition, if I simply want to read the entire file into the scalar using read(), how would I do that, since I don't know the length (in bytes) to ask for? Honestly, I did read some man pages for read, seek, truncate, tell, but I must be missing something, or making a blatantly obvious mistake.

Any help you can provide is much appreciated.
Thanks! --Kozz