Beefy Boxes and Bandwidth Generously Provided by pair Networks
Come for the quick hacks, stay for the epiphanies.
 
PerlMonks  

Re: Clobber instead of append

by Mr_Person (Hermit)
on May 26, 2005 at 03:58 UTC ( [id://460500]=note: print w/replies, xml ) Need Help??


in reply to Clobber instead of append

You can't read and write to the file at the same time like that. You're certainly free to use the same file handle, and that looks like that's what you meant to do with the open modes you chose. Just read in the whole file, then seek to the beginning, write out what you want to, and truncate it to the length of what you've written.

Example:

open(FILE, "+<$file"); my $temp; while(<FILE>) { $temp .= $_; } seek(FILE,0,0); print FILE $temp; truncate(FILE,tell(FILE)); close(FILE);

Of course, you'll want to add some dies to that.

If you're worried about memory usage, I'd suggest reading the file in one line at a time, writing out to a temp file one line at a time, then just moving the temp file over the original (don't forget to preserve permissions).

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://460500]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others having a coffee break in the Monastery: (6)
As of 2024-04-23 12:04 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found