perl and eof detection
am 05.10.2007 15:37:18 von Mark SegerI'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, "
{
printf "EOF: %d\n", eof(TEST);
while (!eof(TEST))
{
$line=
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=
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