Beefy Boxes and Bandwidth Generously Provided by pair Networks
Syntactic Confectionery Delight
 
PerlMonks  

Re: Help in read and write to file at a same time in same file.

by clueless newbie (Friar)
on Apr 04, 2011 at 14:35 UTC ( #897335=note: print w/ replies, xml ) Need Help??


in reply to Help in read and write to file at a same time in same file.

Just For Fun: ... to update a file "in place".

... open(my $READER,'+<',$Filename_S) or die "Can't open '$Filename_S'! $!"; open(my $WRITER,'+<',$Filename_S) # Don't use + '+>' or die "Can't open '$Filename_S'! $!"; # The overflow buffer: my @Buffer_a; while (<$READER>) { # Read (past tense) a line - buffer its replacement ... # Modify the line here! my $Update_s=... push(@Buffer_a,$Update_s); # Write from the overflow buffer if we can ... while (@Buffer_a && length($Buffer_a[0]) < tell($READER)-tell( +$WRITER)) { # Enough room to write $Buffer_a[0] so write it ... print $WRITER shift(@Buffer_a); }; }; # Nothing more to read ... close($READER) or die "Can't close '$Filename_S'! $!"; # If there's anything in the buffer write it ... while (@Buffer_a) { print $WRITER shift(@Buffer_a); }; # Truncate the file, in case, what we're writing is shorter than w +hat we read truncate($WRITER,tell($WRITER)); # ... and close close($WRITER) or die "Can't close '$Filename_S'! $!"; ...
Be aware that if something should happen during the update one may be "up the creek without a paddle".


Comment on Re: Help in read and write to file at a same time in same file.
Download Code

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others having an uproarious good time at the Monastery: (12)
As of 2014-08-22 10:02 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The best computer themed movie is:











    Results (153 votes), past polls