Question

im stucked with the following:

I try to pipe a "$ua->get($url)" in a forked process to the parent process, like this:

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;

I get this error:

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.

the $ua object definitively has a "decoded_content" method, but its not callable after it gets through the pipe (other methods, such as "is_success" also dont work...).

Whats a possible solution here? Any help would be very appreciated.

Was it helpful?

Solution

At the first, you can't write HTTP::Response into the stream directly. The error mean the string that written as "HTTP::Response..." haven't method decoded_content. You must write string got from decoded_content, and read as the string.

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;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top