[Date Prev][Date Next][Thread Prev][Thread Next] [Search] [Date Index] [Thread Index]

Re: [MacPerl] How to modify a text file



On Tue, Jun 08, 1999 at 11:30:51AM -0400, Ronald J Kimball wrote:
> Open for read-write access:
> 
> 
> open(FH, "+<file.txt") or die "Unable to open file.txt: $!\n";
> {
>   local $/;
>   $_ = <IN>;
> }
> 
> #(Do some operations on $_ here)
> 
> seek(FH, 0, 0) or die "Unable to seek in file.txt: $!\n";
> print FH;


P.S.  I forgot an important step here, which is to truncate the file in
case the new text is shorter than the original.

The simple way would be to truncate(FH, 0) right after the seek:

seek(FH, 0, 0) or die "Unable to seek in file.txt: $!\n";
truncate(FH, 0) or die "Unable to truncate file.txt: $!\n";
print FH;


but you might prefer this way, because of concerns about having the data
only in memory for any period of time:

seek(FH, 0, 0) or die "Unable to seek in file.txt: $!\n";
print FH;
$tell = tell(FH) or die "tell() returned 0 for file.txt: $!\n";
# We don't expect tell() to return 0, but if it does,
# we do not want to truncate().
truncate(FH, $tell) or die "Unable to truncate file.txt: $!\n";


Ronald

===== Want to unsubscribe from this list?
===== Send mail with body "unsubscribe" to macperl-request@macperl.org