How to get the result of curl in a variable in Perl if I call it using backtics?

I am trying to get a curl call response to a perl variable.

my $foo = `curl yadd yadda`; print $foo; 

does not work. When I run this on the command line, a call to curl correctly outputs all the output to the terminal, but the variable is not populated with this data.

Is there a way to do this without installing and calling Perl curl lib?

+7
perl curl backticks
source share
8 answers

He probably posts his stuff to stderr. Try

 my $foo = `curl yadd yadda 2>&1`; 
+12
source share

You can also consider LWP :: UserAgent or even LWP :: Simple .

+5
source share

What do you really want to do? Use curl at all costs or grab the contents of a web page?

An easier way to do this (which does not use any external programs that may or may not be installed on the following computer, where you need to do this):

 use LWP::Simple; my $content = get("http://stackoverflow.com/questions/1015438/") or die "no such luck\n"; 

If you want to find out why the GET failed or to capture multiple pages from the same site, you will need to use a little more equipment. perldoc lwpcook helps you get started.

+4
source share

In shell 2> redirection of fileno 2 means. Fileno 2 is always what the program sees as stderr. Similarly, fileno 0 is stdin, and fileno 1 is stdout. So, when you say 2>&1 , you are telling the shell to redirect stderr (fileno 2) to stdout (fileno 1). Since the backticks operator uses the shell to run the command you specify, you can use the shell redirection, so

 my $foo = `curl yadda yadda 2>&1`; 

tells curl to redirect its output to stdout, and since the backtick statement catches stdout, you get what you were looking for.

+3
source share

Try the following:

 $var = `curl "http://localhost" 2>/dev/null`; print length($var) 

curl displays progress information in stderr, redirecting to / dev / null makes it easier to see what is happening.

0
source share

This works on my system:

 #!/usr/bin/perl use strict; use warnings; my $output = `curl www.unur.com`; print $output; __END__ C:\> z1 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"><html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> 

and etc.

0
source share

You can open the channel as if it were a file.

 $url = "\"http://download.finance.yahoo.com/d/quotes.csv?s=" . "$symbol&f=sl1d1t1c1ohgvper&e=.csv\""; open CURL, "curl -s $url |" or die "single_stock_quote: Can't open curl $!\n"; $line = <CURL>; close CURL; 
0
source share

It is possible that some output you want to capture is in standard err, not standard. Try the following:

 my $foo = system "curl http://www.stackoverflow.com"; print $foo; 
-one
source share

All Articles