in reply to truncate a file from top
But I assume since it's a log file that you want to chop off the beginning:truncate('test.dat', 1024);
Of course, this method has problems too, in that additional lines could theoretically be appended to the file between the read and the write and therefore lost. File locking / unlocking probably isn't a viable solution, but you can just assume that up to x number of bytes might be written to the file between read and write, and edit your truncate accordingly:use strict; use warnings; my $fname = 'test.dat'; my $crop = 1024; my $handle; open($handle, $fname); $_ = (stat($handle))[7]; if ($_ > $crop) { seek($handle, $_ - $crop, 0); read($handle, $_, $crop); close($handle); open($handle, ">$fname"); print $handle $_; } close($handle);
EDIT: zentara's solution solves that problem, and is much more elegant if you assume that the file will always be larger than the truncate size. ++my $crop = 1024; my $margin = 64; ... read($handle, $_, $crop + $margin);
|
|---|