如何使用Perl以流方式读取文本文件

时间:2013-10-04 05:39:59

标签: perl

它可以在文件中显示文本,但是,在我在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 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

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

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

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

man tail > foo

2.慢慢打印文件:

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

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

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

答案 2 :(得分: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

答案 3 :(得分:0)

以下内容也适用:

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