in reply to Limiting log file size

Well, as a first start, I'd try something like this:
#!/usr/bin/perl my $FILE = "the_log_file"; my $MAXSIZE = 2**20; # 1 meg exit 0 unless -s $FILE > $MAXSIZE; @ARGV = $FILE; # set diamond to file undef $/; # slurp mode $^I = ""; # enable in-place editing while (<>) { substr($_, 0, $MAXSIZE - length) = ""; # save last portion s/.*\n//; # toss one line so it comes out at a line boundary print; }

-- Randal L. Schwartz, Perl hacker

Replies are listed 'Best First'.
Re: •Re: Limiting log file size
by Juerd (Abbot) on Apr 02, 2002 at 18:10 UTC

    undef $/; # slurp mode
    $^I = ""; # enable in-place editing

    This sounds like a nice job for Tie::File.

    #!/usr/bin/perl -w use Tie::File; use strict; my $max = 512; my $file = 'syslog'; tie my @lines, 'Tie::File', $file; my $size = 0; for my $line (reverse -@lines .. -1) { if (($size += length $lines[$line]) > $max) { splice @lines, 0, (@lines + $line + 1); last; } } untie @lines;
    (Didn't use negative splice length, because Tie::Splice seems to be unable to handle it.)

    U28geW91IGNhbiBhbGwgcm90MTMgY
    W5kIHBhY2soKS4gQnV0IGRvIHlvdS
    ByZWNvZ25pc2UgQmFzZTY0IHdoZW4
    geW91IHNlZSBpdD8gIC0tIEp1ZXJk