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

Hi Monks!, i want to tail -f a access log and only print 'new' entries, not the entire logfile. I currently have this code, but that also prints the old contents which i don't want..

#!/usr/bin/perl use strict; use warnings; my $logfile = "/var/log/httpd/agent1_access.log"; open(FH,'<',$logfile) || handle_error(); # typical open call for (;;) { while (<FH>) { print "$_"; } # eof reached on FH, but wait a second and maybe there will be mor +e output sleep 1; seek FH, 0, 1; # this clears the eof flag on FH }

Replies are listed 'Best First'.
Re: tailing a file without printing its entire contents
by BrowserUk (Patriarch) on Aug 07, 2014 at 12:00 UTC

    If you place the seek, with to-end, above the while loop, it'll skip over the existing content the first time you read the file:

    use strict; use warnings; my $logfile = "/var/log/httpd/agent1_access.log"; open(FH,'<',$logfile) || handle_error(); # typical open call for (;;) { seek FH, 0, 2; # this clears the eof flag on FH # eof reached on FH, but wait a second and maybe there will be mor +e output sleep 1; while (<FH>) { print "$_"; } }

    With the rise and rise of 'Social' network sites: 'Computers are making people easier to use everyday'
    Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
    "Science is about questioning the status quo. Questioning authority".
    In the absence of evidence, opinion is indistinguishable from prejudice.
      Thanks, exactly what i was looking for!
Re: tailing a file without printing its entire contents
by roboticus (Chancellor) on Aug 07, 2014 at 12:04 UTC

    ChRy0:

    Another module that may be useful: File::Tail.

    ...roboticus

    When your only tool is a hammer, all problems look like your thumb.

Re: tailing a file without printing its entire contents
by Athanasius (Archbishop) on Aug 07, 2014 at 11:58 UTC
Re: tailing a file without printing its entire contents
by bulrush (Scribe) on Aug 09, 2014 at 13:02 UTC
    Another possibility, untested.
    open(FH, 'logfile.txt') || die "Could not op en logfile.txt"; @arr=<FH>; # Read whole file into array. my $lines=10; # Print last 10 lines my $start=$#arr-$lines; for $i (@arr($start..$#arr)) { print "$arr[$i]\n"; } close(FH);
    Perl 5.8.8 on Redhat Linux RHEL 5.5.56 (64-bit)