Beefy Boxes and Bandwidth Generously Provided by pair Networks
"be consistent"

Skipping to the End of a File

by madhatter (Sexton)
on Jan 14, 2001 at 21:54 UTC ( #51779=perlquestion: print w/ replies, xml ) Need Help??
madhatter has asked for the wisdom of the Perl Monks concerning the following question:

I know I could use an if statement and a boolean variable, but I'm sure there has to be another way to make Ovid's code to go straight to the last line, even when the file has a couple hundred lines or what have you in it already.

while(1){ while(<FILE>){ print $_; seek(FILE,0,1); } sleep(1); }

It'll print out the entire file, then start printing the last line as it is written. Ideally, this would:
A - Ignore everything except lines that are added after the program is run .. or
B - Print the last line of the file, then do its thing printing new lines.

I've tried all sorts of seeks() all over the code, to no avail. Any help would be greatly appreciated.


Comment on Skipping to the End of a File
Download Code
Replies are listed 'Best First'.
Re: Skipping to the End of a File
by moen (Hermit) on Jan 14, 2001 at 22:45 UTC
Re: Skipping to the End of a File
by chipmunk (Parson) on Jan 15, 2001 at 09:05 UTC
    Seek the documentation for seek; then you'll know how to seek to the end of a file: seek(FILE, 0, 2) or die "Can't seek: $!\n";
    For more helpful advice, seek the FAQ How do I do a tail -f in perl?.
Re: Skipping to the End of a File
by BatGnat (Scribe) on Jan 15, 2001 at 09:25 UTC
    I dont know how much slower this is, than the other options, but I normally would use:
    open(file,"<file.txt"); foreach (reverse <FILE>) { print $_; last; } close(file);


    This project cannot be completed successfully as we require - a shrubbery!

      That's not really an efficient solution -- it reads the entire file into memory as a list of lines and then reverses that list before entering the loop block. The previous solutions using seek() or File::Tail are better options.

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://51779]
Approved by root
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others pondering the Monastery: (17)
As of 2015-10-06 15:11 GMT
Find Nodes?
    Voting Booth?

    Does Humor Belong in Programming?

    Results (152 votes), past polls