perl and eof detection

M

Mark Seger

I'm trying to do something similar to 'tail -f', in that I want to read
a file and when new data appears read/print it. Consider the following
and you will see I simply test for eof and if there's data there
read/print and if now, test the eof again. To make this easier to
fiddle with, I added a sleep 1 between eof() calls. I also removed the
print I had after the

#!/usr/bin/perl -w

open TEST, "<test" or die;
while (1)
{
printf "EOF: %d\n", eof(TEST);
while (!eof(TEST))
{
$line=<TEST>;
print $line;
}
sleep 1;
}

I have a second script that simply open ">>test", writes a couple of
records and exist. When I run the script above, it happily reports the
contents of the file file and then starts printing "EOF: 1" as expected.
However, when I then write more to the file eof never changes!

But wait - if I comment out the 'while' line and let it continue to try
to do the reads, I get an unititialized variable on the print as
expected, but when I now print to the file eof shows up as 0 and the
script picks up the new data.

My working hypothesis is that doing the read after eof is caused the
script to reevaluate the file state. To test this theory I uncommented
the while so the script again looks as it does above but this time
inserted an extra "$line=<TEST> right before the sleep. This should
almost always fail, but now when I append to the file the eof state
correctly changes from 1 to 0 and the script begins to work again.
However, not only is this a hack, but if data were written to the file
after the loop exists and before the dummy read is executed I'd lose a
line of data.

I guess my question is what is really going on and is there a more
correct way to determine if there is data in the file before reading it?

I also discovered I could just do a stat() after the first time the file
is flushed and detect changes that way but I guess I'd like to
understand why this happening in the first place.

-mark
 
P

Paul Lalli

I'm trying to do something similar to 'tail -f',

Have you checked the FAQ?

$ perldoc -q tail
Found in /opt2/Perl5_8_4/lib/perl5/5.8.4/pod/perlfaq5.pod
How do I do a "tail -f" in perl?


Paul Lalli
 
M

Mark Seger

yes, and I also found it in faq5 as pointed out by paul in a previous
reply. it also turns out if I can get the same results by doing
something like:

while ($line=<TEST>)
{
}

instead of testing for eof at all, since doing the read on a file
already at the end-of-file also resets the eof marker. alas, I'm still
not sure which is more efficient or if it even makes much a difference.
-mark
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,770
Messages
2,569,583
Members
45,073
Latest member
DarinCeden

Latest Threads

Top