Perl - How to use a process Handle created in a Module in another Perl Script

狂风中的少年 提交于 2019-12-12 02:44:18

问题


Ultimately, what I want to do is to start a process in a module and parse the output in real time in another script.

What I want to do :

  • Open a process Handler (IPC)
  • Use this attribute outside of the Module

How I'm trying to do it and fail :

  • Open the process handler
  • Save the handler in a module's attribute
  • Use the attribute outside the module.

Code example :

#module.pm

$self->{PROCESS_HANDLER};

sub doSomething{
  ...
  open( $self->{PROCESS_HANDLER}, "run a .jar 2>&1 |" );
  ...
}


#perlScript.pl

my $module = new module(...);
...
$module->doSomething();
...
while( $module->{PROCESS_HANDLER} ){
  ...
}

回答1:


Your while statement is missing a readline iterator, for one thing:

while( < {$module->{PROCESS_HANDLER}} > ) { ...

or

while( readline($module->{PROCESS_HANDLER}) ) { ...



回答2:


 

package Thing;
use Moose;
use IO::Pipe;

has 'foo' => (
    is      => 'ro',
    isa     => 'IO::Handle',
    default => sub {
        my $handle = IO::Pipe->new;
        $handle->reader('run a .jar 2>&1'); # note, *no* pipe character here
        return $handle;
    });

1;

package main;
use Thing;
my $t = Thing->new;
say $t->foo->getlines;


来源:https://stackoverflow.com/questions/3015584/perl-how-to-use-a-process-handle-created-in-a-module-in-another-perl-script

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!