Perl大量下载直接到文件(避免RAM过载)

nan*_*ocv 3 perl download out-of-memory large-files

我正在尝试将具有1 GB aproximated大小的文件下载到具有1 GB RAM内存的服务器,因此如果我尝试将其下载到变量(下面的代码)中,则操作系统会因RAM过载而终止进程.

require LWP::UserAgent;

my $ua = LWP::UserAgent->new;
$ua->timeout(3600);
$ua->env_proxy;

my $response = $ua->get('http://example.com/largefile.xml');

if ($response->is_success) {
    print "File downloaded\n";
}
else {
    die $response->status_line;
}
Run Code Online (Sandbox Code Playgroud)

我认为可行的唯一方法是使用system("wget ...")(或卷曲或类似的东西),但我确信有一种正确的方法可以直接使用Perl.

你知道任何方法或选项直接下载到文件而不使用系统调用吗?

Sob*_*que 8

是的.看LWP::UserAgentget方法:

$ ua> get($ url,$ field_name => $ value,...)

以":"开头的字段名称是特殊的.这些不会初始化请求的标头,但会确定如何处理响应内容.识别以下特殊字段名称:

:content_file   => $filename
Run Code Online (Sandbox Code Playgroud)

如果:content_file选项提供了$ filename ,则响应内容将保存在此处而不是响应对象中.

注意 - 它可能不会很好地处理文件系统错误,因此请检查您是否可以写入该位置.(权限,目录存在等)