2013-06-28 99 views
0

IM stucked下列要求:通過管道Perl的管道對象不正常工作

我嘗試管一個「$ UA->獲取($網址)」的派生進程的父進程,就像這樣:

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對象明確有「decoded_content」的方法,但它不是調用它獲得通過管道後(其它方法,如「is_success」也不工作......)。

這裏有什麼可能的解決方案?任何幫助將非常感激。

回答

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; 
+0

謝謝,這是有道理的;)。 – carrot