通过管道的Perl管道对象不能正常工作

时间:2013-06-28 08:38:42

标签: perl fork pipe user-agent lwp

我坚持以下几点:

我尝试在分叉进程中将“$ ua-> get($ url)”传递给父进程,如下所示:

use LWP::UserAgent;
use IO::Handle;

pipe my $ua_reader, my $ua_writer;
my $url = "http://some-sample-html-file";

my $ua = LWP::UserAgent->new;
$ua->timeout(1);

my $ua_process = fork();
if( $ua_process == 0 ) {
    close $ua_reader;
    print $ua_writer $ua->get($url);
    exit 0;
}

do {
    $ua_process = waitpid(-1, 0);
} while ($ua_process >= 0);
close $ua_writer;
my $response = $ua_reader->getline;
close $ua_reader;

print $response->decoded_content;

我收到此错误:

Can't locate object method "decoded_content" via package "HTTP::Response=HASH(0x19045f0)" (perhaps you forgot to load "HTTP::Response=HASH(0x19045f0)"?) at ./uafork.pl line 26.
$ ua对象最终有一个“decoding_content”方法,但是在通过管道后它不可调用(其他方法,例如“is_success”也不起作用......)。

这里有什么可能的解决方案吗?任何帮助都将非常感激。

1 个答案:

答案 0 :(得分:2)

首先,您无法直接将HTTP :: Response写入流中。该错误意味着写为“HTTP :: Response ...”的字符串没有方法decoded_content。 你必须从decode_content写入字符串,并读作字符串。

use LWP::UserAgent;
use IO::Handle;
use Encode;

pipe my $ua_reader, my $ua_writer;
my $url = "http://some-sample-html-file";

my $ua = LWP::UserAgent->new;
$ua->timeout(1);

my $ua_process = fork();
if( $ua_process == 0 ) {
    close $ua_reader;
    print $ua_writer encode_utf8 $ua->get($url)->decoded_content;
    exit 0;
}

do {
    $ua_process = waitpid(-1, 1);
} while ($ua_process != 0);
close $ua_writer;
my $response = $ua_reader->getline;
close $ua_reader;

print $response;