-1

它可以在文件中显示文本,但是,在我在 gedit 中添加新文本后,它不会显示更新的文本。

sub start_thread {
my @args = @_;
print('Thread started: ', @args, "\n");
open(my $myhandle,'<',@args) or die "unable to open file";  # typical open call
for (;;) {
    while (<$myhandle>) {
    chomp;
    print $_."\n";
    }
    sleep 1;
    seek FH, 0, 1;      # this clears the eof flag on FH
}
}

更新视频 https://docs.google.com/file/d/0B4hnKBXrOBqRWEdjTDFIbHJselk/edit?usp=sharing

https://docs.google.com/file/d/0B4hnKBXrOBqRcEFhU3k4dUN4cXc/edit?usp=sharing

如何为更新的数据打印 $curpos

for (;;) {
        for ($curpos = tell($myhandle); $_ = <$myhandle>;
            $curpos = tell($myhandle)) {
             # search for some stuff and put it into files
         print $curpos."\n";
        }
        sleep(1);
        seek(FILE, $curpos, 0);
    }
4

4 回答 4

0

而不是这个:

seek $myhandle, 0, 1;      # this clears the eof flag on FH

你可以尝试这样的事情:

my $pos = tell $myhandle;
seek $myhandle, $pos, 0;      # reset the file handle in an alternate way
于 2013-10-04T07:06:55.310 回答
0

文件系统试图为您提供正在阅读的文件的一致视图。要查看更改,您需要重新打开文件。

要查看此示例,请尝试以下操作:

1.创建一个包含 100 行文本的文件,一个手册页,例如:

man tail > foo

2.慢慢打印文件:

cat foo | perl -ne 'print; sleep 1;'

3.在此过程中,在另一个 shell 或编辑器中,尝试通过删除大多数行来编辑文件

结果:文件将继续缓慢打印,就好像您从未编辑过它一样。只有当您再次尝试打印时,您才会看到更改。

于 2013-10-04T07:13:34.310 回答
0

就像我说的 - 它对我有用。对脚本的更改很少 - 只是最少的清理。

脚本:test_tail.pl

#!/usr/bin/perl

sub tail_file {
    my $filename = shift;
    open(my $myhandle,'<',$filename) or die "unable to open file";  # typical open call
    for (;;) {
        print "About to read file...\n";
        while (<$myhandle>) {
            chomp;
            print $_."\n";
        }
        sleep 1;
        seek $myhandle, 0, 1;      # this clears the eof flag on FH
    }
}

tail_file('/tmp/test_file.txt');

然后:

echo -e "aaa\nbbb\nccc\n" > /tmp/test_file.txt
# wait a bit
echo -e "ddd\neee\n" >> /tmp/test_file.txt

同时(在不同的终端);

$ perl /tmp/test_tail.pl 
About to read file...
aaa
bbb
ccc

About to read file...
About to read file...
About to read file...
ddd
eee
于 2013-10-04T07:33:14.590 回答
0

以下也将起作用:

my $TAIL = '/usr/bin/tail -f';  # Adjust accordingly
open my $fh, "$TAIL |"
    or die "Unable to run $TAIL : $!";
while (<$fh>) {
    # do something
}
于 2013-10-04T10:29:23.363 回答