Truncating just the superfluous newlines should work, too. This would avoid rewriting the entire file, and/or reading it into memory.
open my $fh, "+<", $fname or die $!;
my $pos = (-s $fh) - 1;
my $s;
do {
seek $fh, $pos--, 0;
read $fh, $s, 1;
} while $s eq "\n";
truncate $fh, $pos + 3;
(On Windows you'd need to truncate at $pos + 4, or else you'd have just a trailing \r, not a complete \r\n.)
Update: ww remarked via /msg that on Windows ActiveState Perl < 5.14, truncate only works on closed files (according to his tests), but that as of 5.14(.2) it does behave as expected. I don't have Windows here to verify, so I can only pass this on as is. Thanks anyway!
|