我正在尝试将curl调用的响应转换为perl中的变量。

my $foo = `curl yadd yadda`;

print $foo;

不起作用。当我在命令行运行它时,curl调用在终端中正确打印所有输出,但变量没有填充该数据。

有没有办法在不安装和调用Perl curl lib的情况下执行此操作?

有帮助吗?

解决方案

它可能会将其内容发送给stderr。尝试

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

其他提示

您也可以考虑查看 LWP :: UserAgent 甚至 LWP :: Simple

你真的想做什么?不惜一切代价使用 curl ,或者抓住网页的内容?

这样做的一种更为流行的方式(依赖于没有外部程序可能会或可能不会安装在您需要执行此操作的下一台机器上)将是:

use LWP::Simple;

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

如果您想了解GET失败的原因,或者从同一站点获取多个页面,您需要使用更多的机器。 perldoc lwpcook 将帮助您入门。

在shell中 2> 表示重定向fileno 2. Fileno 2始终是程序看到的stderr。类似地,fileno 0是stdin,fileno 1是stdout。所以,当你说 2>& 1 时,你告诉shell将stderr(fileno 2)重定向到stdout(fileno 1)。由于反引号运算符使用shell来运行您指定的命令,因此可以使用shell重定向,所以

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

告诉curl将其输出重定向到stdout,并且由于反引号操作符捕获stdout,你得到你想要的东西。

试试这个:

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

curl 显示有关stderr的进度信息,将其重定向到/ dev / null可以更容易地查看正在发生的事情。

这适用于我的系统:

#!/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">

您可以像打开文件一样打开管道。

$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;

您可能想要捕获的某些输出是标准错误,而不是标准输出。试试这个:

my $foo = system "curl http://www.stackoverflow.com";
print $foo;
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top