Beefy Boxes and Bandwidth Generously Provided by pair Networks
Syntactic Confectionery Delight


by turnstep (Parson)
on Mar 12, 2001 at 23:05 UTC ( #63906=snippet: print w/replies, xml ) Need Help??

A perl program that acts similar to "tail" in unix. Just provide the name of the file, an optional number of lines, and an optional characters per line.


## PerlTail
## Does a "tail" of a file using seek.

use strict;

my $bigfile = shift or die "Usage: $0 filename <lines> <linesize>\n";

my $linesback = shift || 10; ## How many "lines" back to read

my $charsperline = shift || 80; ## A rough guess

open(BIG, $bigfile) or die "Could not open $bigfile: $!\n";

## Make a reasonable guess as to how far back to go.
my $gobackchars = $linesback*$charsperline+1;

## Figure out how big it is
my $filesize = -s $bigfile;

## We do not want to go back *too* far:
$gobackchars = $filesize if $gobackchars > $filesize;


## We probably arrived in the middle of a line,
## so throw out everything to the start of a new line

## Now we print out the rest of the lines:
print while(<BIG>);


Update: There is noting wrong with any of the programs/modules already out there. This is just a *snippet*, a quick little piece of code I wrote that demonstrates a good use of seek. Sheesh! :)

Replies are listed 'Best First'.
Re: Perltail
by fundflow (Chaplain) on Mar 12, 2001 at 23:40 UTC
    Have you seen this in Perl Power Tools?

(tye)Re: Perltail
by tye (Sage) on Mar 12, 2001 at 23:48 UTC

    When I ask for the last 10 lines of a file, I usually don't like to instead see the last 800 characters of the file (minus any partial line).

    Sorry, I find this a pretty poor reinvention of this wheel.

            - tye (but my friends call me "Tye")
(ar0n: CPAN) Re: Perltail
by ar0n (Priest) on Mar 13, 2001 at 02:15 UTC
Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: snippet [id://63906]
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others contemplating the Monastery: (6)
As of 2021-04-14 10:50 GMT
Find Nodes?
    Voting Booth?

    No recent polls found