Beefy Boxes and Bandwidth Generously Provided by pair Networks
Do you know where your variables are?
 
PerlMonks  

Re: tail a file in perl

by SarahM (Monk)
on Oct 23, 2002 at 14:25 UTC ( [id://207400]=note: print w/replies, xml ) Need Help??


in reply to tail a file in perl

Here is a piece of code that I've written to get the last lines in a file for one of my programs:
my @lines; my $currLine = 0; my $maxLines = 10; # Go through the file, saving the last $maxLines while (<>){ $lines[$currLine] = $_; $currLine++; $currLine = 0 if ($currLine == $maxLines); } # Print out the last $maxLines for (1..$maxLines){ print $lines[$currLine]; $currLine++; $currLine = 0 if ($currLine == $maxLines); }
I think this code is simple enough to understand what is going on, but if you need to explain more I will. (I have to get some real work done first ;)

Replies are listed 'Best First'.
Re: Re: tail a file in perl
by blokhead (Monsignor) on Oct 23, 2002 at 17:22 UTC
    Or a slightly more Perl-flavored version of your C-flavored code:
    my @lines; my $maxlines = 10; while (<>) { push @lines, $_; shift @lines if (@lines > $maxlines); } print join("\n", @lines) . "\n";
    Instead of using a circular array, this uses @lines as a FIFO buffer, storing the last $maxlines lines, using push and shift. Much less code! I'm not sure if this is the way it's implemented in the aforementioned perlfaq5 and other discussions...

    Update: The solutions here using seek to read blocks starting at the end are going to be more efficient than this one (as the whole file is not read), although this solution is fine for reasonable-sized files.. Plus I think it's much simpler to comprehend.

    blokhead

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://207400]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others about the Monastery: (4)
As of 2024-04-19 11:44 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found