Search code examples
perlfilelwplwp-useragent

How do I process the response as a file without using the :content_file option?


Example code:

my $ua = LWP::UserAgent->new;  
my $response = $ua->get('http://example.com/file.zip');
if ($response->is_success) {
    # get the filehandle for $response->content
    # and process the data
}
else { die $response->status_line }

I need to open the content as a file without prior saving it to the disk. How would you do this?


Solution

  • You can open a fake filehandle that points to a scalar. If the file argument is a scalar reference, Perl will treat the contents of the scalar as file data rather than a filename.

    open my $fh, '<', $response->content_ref;
    
    while( <$fh> ) { 
        # pretend it's a file
    }