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

I have some code that does somthing like this:
open FILE, "+<$filename"; undef $/; $old_data = <FILE>; #do some stuff seek FILE, 0, 0; print FILE $new_data;
This works fine, except when $new_data is smaller than $old_data. In that case, I get the end of $old_data left in my file, which isn't what I want. Is there a way I can either shrink the file to zero size instead of just seeking to the beginning, or tell perl to end the file at the current cursor position, ignoring everything after it? Or should I just give in and close the file and re-open it?

--
Ryan Koppenhaver, Aspiring Perl Hacker
"I ask for so little. Just fear me, love me, do as I say and I will be your slave."

Replies are listed 'Best First'.
(Ovid) Re: read-write troubles
by Ovid (Cardinal) on Nov 03, 2000 at 21:55 UTC
    open FILE, "+<$filename" or die "I checked a return call: $!\n"; { local $/; # Always localize this so it doesn't interfere with othe +r parts of the program. $old_data = <FILE>; } #do some stuff seek FILE, 0, 0 or die "Can't seek on $filename: $!\n"; print FILE $new_data or die "Can't print to $filename: $!\n"; truncate FILE, tell(FILE) or die "Can't truncate $filename: $!\n"; close FILE or die "Can't close $filename: $!\n";

    Cheers,
    Ovid

    Join the Perlmonks Setiathome Group or just go the the link and check out our stats.

RE: read-write troubles
by Albannach (Monsignor) on Nov 03, 2000 at 21:52 UTC
        And to forstall your next question, look at flock. :-)