Perl轮询文件句柄?

时间:2015-02-12 12:46:32

标签: perl

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获取某些东西时我无法做其他事情

1 个答案:

答案 0 :(得分:5)

是的,有。您需要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是在线程之间来回传递数据的一种很好的方法。 (如果您认为自己想要走那条路线,请参阅:Perl daemonize with child daemons