2015-04-04 63 views
-4

文件没有下载,请帮忙。正在下载文本文件:Perl

#!/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"); 
    } 
} 
+2

在代码中使用'use warnings'和'use strict'。 – serenesat 2015-04-04 15:40:17

+0

我使用严格和警告。它说$ $ response,content和line需要一个明确的包名称。我检查了perl模块是否存在cpan LWP :: UserAgent和cpan HTTP :: Response通过命令行。它说这两个模块都是最新的 – phani 2015-04-04 16:35:10

+1

这很有趣。即使没有这些措施,我也会在E:\ Perl \ source \ resp.pl第10行中得到'未引用的字符串“响应”与将来的保留字冲突。','E:\ Perl \ source \ resp中的语法错误。 pl行6附近“$ line(”','E:\ Perl \ source \ resp.pl第17行附近的语法错误,}“','执行E:\ Perl \ source \ resp.pl中止编译错误。“你真的无法自己解决这些问题吗? ' – Borodin 2015-04-04 22:25:26

回答

2

您的程序有许多问题。其中主要在这条线是

response = $ua->get('www.ndbserver.rutgers.edu/files/ftp/NDB/coordinates/na-biol/$line'); 
  • 您正在尝试将分配给response$line值不被插入到URL,因为你这是不是一个变量名

  • 使用单引号

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

  • 的URL没有方案 - 它应该http://

从这些点

除了开始,你应该解决这些问题

  • 必须始终use strictuse warnings的顶部每你写的Perl程序。在shebang线上添加-w远远不如

  • 您应该use而不是requireLWP::UserAgent。而且也没有必要也use HTTP::Response,因为它是加载LWP

    的一部分
  • 你应该总是使用与词法文件句柄三参数形式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": $!}; 
}