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
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.