Convert this in Perl curl -v -H "AUTH_USER:$user" "$url" 1> "$tmpfile" 2> "$hdrfile"

703 Views Asked by At

I am trying to convert this shell command into perl I am using use WWW::Curl::Easy;

I want to write the verbose in a different file and i want to get the URL content into a different file . Till now i have been able to curl the URL and add header to it as well .

Now I want to just write the as shell command mentions output from 1> into a file and

2> into antohter file as it is there in shell

my $curl = WWW::Curl::Easy->new();
        $curl->setopt(CURLOPT_HEADER,1); 
        $curl->pushopt(WWW::Curl::Easy::CURLOPT_HTTPHEADER,['AUTH_USER:John']);
        $curl->setopt(WWW::Curl::Easy::CURLOPT_URL,"www.abc.com");
        $curl->setopt(CURLOPT_VERBOSE,1);

how do i put the content of www.abc.com that is

<html>
<body>
<marquee>abc is up </marquee>
</body>
</html>

into one file

And this into another file

> GET / HTTP/1.1
Host: abc-01
Accept: */*
AUTH_USER:hojn

< HTTP/1.1 200 OK
......
2

There are 2 best solutions below

3
On

A cursory reading of the documentation and libcurl docs reveals that you probably need:

    # A filehandle, reference to a scalar or reference to a typeglob can be used here.
    my $response_body;
    $curl->setopt(CURLOPT_WRITEDATA,\$response_body);

    my $response_header;
    $curl->setopt(CURLOPT_WRITEHEADER,\$response_header);
2
On

When using libcurl, it's useful to have its documentation handy.

Browsing through the options, we find CURLOPT_HEADERFUNCTION & WRITEHEADER and CURLOPT_WRITEFUNCTION & WRITEDATA.

use strict;
use warnings;

use Net::Curl::Easy qw( /^CURLOPT_/ );

my $url = 'http://stackoverflow.com/';

my $easy = Net::Curl::Easy->new();

open(my $fh_header, '>:raw', 'header.out') or die $!;
open(my $fh_data,   '>:raw', 'data.out'  ) or die $!;

$easy->setopt(CURLOPT_URL,         $url);
$easy->setopt(CURLOPT_WRITEHEADER, $fh_header);
$easy->setopt(CURLOPT_WRITEDATA,   $fh_data);
$easy->perform();

Note: I used Net::Curl over WWW::Curl because I know and trust it. The above should also work with WWW::Curl as long as it provides a Perl-aware default for CURLOPT_WRITEFUNCTION and CURLOPT_HEADERFUNCTION. It it doesn't, you'll need to provide values for those options too.