Beefy Boxes and Bandwidth Generously Provided by pair Networks
No such thing as a small change

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.


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
Domain Nodelet?
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 perusing the Monastery: (6)
As of 2022-01-24 22:47 GMT
Find Nodes?
    Voting Booth?
    In 2022, my preferred method to securely store passwords is:

    Results (65 votes). Check out past polls.