Perl 轮询文件句柄?

Perl polling a file handle?

use strict;
use warnings;

my $file = 'SnPmaster.txt';
open my $info, $file or die "Could not open $file: $!";

while( my $line = <$info>)  {   
    print $line;    
    last if $. == 2;
}

close $info;

在我看来,以上内容建议从文件句柄 (while( my $line = <$info>)) 读取。

但是有没有一种方法可以读取而不是使用 while 循环?

open FH,
    "executable_that_prints_every_once_in_awhile"
    or die 'Cannot open FH';
while (1){
    # do something which doesnt get blocked by <FH>

    if (my $line from <FH>) {           <---- is there something like it?
        print $line;
    }

    last if eof <FH>;
}

例如,轮询是否有来自文件句柄的输入?

while( my $line = <$info>) 的问题是它会阻塞,所以我在等待从 FH 那里得到东西时不能做其他事情

是的,有。您需要 IO::Selectcan_read 函数。

类似于:

#!/usr/bin/perl
use strict;
use warnings;
use autodie;

use IO::Select;

my $selector = IO::Select->new();

open( my $program, "-|", "executable_that_prints_every_once_in_awhile" );
$selector->add($program);

foreach my $readable_fh ( $selector->can_read() ) {

    #do something with <$readable_fh>
}

或者 - 使用 threadsfork 的并行代码:

#!/usr/bin/perl
use strict;
use warnings;
use autodie;
use threads;

sub reader_thread { 
   open ( my $program, "-|", "executbale_file" );
   while ( my $line =  <$program> ) {
      print $line;
   }
}

threads -> create ( \&reader_thread );

while ( 1 ) {
   #do something else
}

#sync threads at exit - blocks until thread is 'done'. 
foreach my $thr ( threads -> list ) {
  $thr -> join();
}

一般来说,当您需要做的不仅仅是微不足道的 IPC 时,我会建议使用线程,而对于一般性能,我建议使用分叉。 Thread::Queue is quite a good way of passing data back and forth between threads, for example. (See: Perl daemonize with child daemons 如果你认为你想走那条路)