Rate this page

Flattr this

Fetch the content of a given URL in Perl using LWP::Simple

Tested on

Debian (Lenny, Squeeze)
Ubuntu (Lucid, Precise, Trusty)

Objective

To fetch the content located at a given URL in Perl using the module LWP::Simple

Scenario

Suppose that you wish to fetch the content of the URL http://www.example.com/ and place it in the Perl variable $content. You have chosen to do this using the module LWP::Simple.

Method

The module LWP::Simple provides a function named get which fetches the content of a URL given as its first and only argument:

use LWP::Simple;

my $url = 'http://www.example.com/';
my $content = get($url);
if (!defined $content) {
    die "failed to fetch URL $url";
}

A response of undef indicates that the transfer failed, but the reason for the failure is not recorded. Metadata provided in the HTTP headers is similarly unavailable to the caller.

Further reading

Tags: http | perl