下载文本文件:Perl

时间:2015-04-04 15:24:50

标签: perl lwp-useragent

文件没有下载,请帮忙。

#!/usr/bin/perl -w
require HTTP::Response;
require LWP::UserAgent;
open (INPUT, "ndb_id_file.txt") or die "can't open ndb_id_file.txt";
@input = <INPUT>
foreach $line(@input) {
    $ua = LWP::UserAgent->new;
    $ua->env_proxy('http');
    $ua->proxy(['http', 'ftp'],'http://144020019:*******@netmon.****.ac.in:80');
    response = 
        $ua->get('www.ndbserver.rutgers.edu/files/ftp/NDB/coordinates/na-biol/$line');
    if ($response->is_success) {
        $content = $response->content();
        open(OUT,">$line.pdb") or die "Output file $line cannot be produced... Error...";
        print (OUT "$content");
    }
}

1 个答案:

答案 0 :(得分:2)

您的计划存在许多问题。主要是这一行

response = $ua->get('www.ndbserver.rutgers.edu/files/ftp/NDB/coordinates/na-biol/$line');
  • 您正在尝试分配给response,这不是变量名称

  • $line的值未插入到网址中,因为您使用的是单引号

  • $line的内容以换行结束,应使用chomp

  • 删除
  • 网址没有计划 - 它应以http://

  • 开头

除了这些要点之外,你应该解决这些问题

  • 必须始终 use strictuse warnings位于您编写的每个 Perl程序的顶部。在shebang线上添加-w远远低于

  • 您应该use而不是require LWP::UserAgent。并且也没有必要use HTTP::Response因为它是作为LWP的一部分加载的

  • 您应该始终使用带有词法文件句柄的{em>三参数形式的open。如果open失败,您应该打印一个die字符串,其中包含$!的值,该字符串会为失败提供原因

  • 您应该使用while一次一行地读取文件中的数据,除非您有充分的理由在一次内存中需要所有数据

  • 每次循环时都无需创建新的用户代理$ua。只需创建一个并使用它来获取每个URL

  • 您应该使用decoded_content代替content来获取HTTP::Response邮件的内容,以防其被压缩

这是一个包含所有这些修复程序的程序。我还没有能够测试它,但它确实编译了

#!/usr/bin/perl
use strict;
use warnings;

use LWP::UserAgent;

my $in_file = 'ndb_id_file.txt';

open my $fh, '<', $in_file or die qq{Unable to open "$in_file" for input: $!};

my $ua = LWP::UserAgent->new;
$ua->env_proxy('http');
$ua->proxy(['http', 'ftp'], 'http://144020019:*******@netmon.****.ac.in:80');

while ( my $line = <$fh> ) {

    chomp $line;
    my $url = "http://www.ndbserver.rutgers.edu/files/ftp/NDB/coordinates/na-biol/$line";
    my $response = $ua->get($url);

    unless ( $response->is_success ) {
      warn $response->status_line;
      next;
    }

    my $content = $response->decoded_content;
    my $out_file = "$line.pdb";

    open my $out_fh, '>', $out_file or die qq{Unable to open "$out_file" for output: $!};
    print $out_fh $content;
    close $out_fh or die qq{Unable to close "$out_file": $!};
}