2014-10-06 104 views
0

我的腳本從FTP下載文件並將文件移動到FTP中的存檔目錄。 我有一個模式來搜索FTP中的文件,並將它放在foreach循環中以將這些文件導入本地目錄。裸語句在perl中的foreach循環中不起作用

my $ftpUser  = 'xxxx'; 
my $ftpPW  = 'xxxxxx'; 
my $FTPHost  = "xxxxxxxxxxx"; 
my $remotefile = 'CAP*.csv'; 
my $archivefile = "/usr/archive/CAP_${file_date_time}.csv"; 

my $ftp = Net::FTP->new($FTPHost); 
$ftp->login($ftpUser, $ftpPW) or die print L1 "Could not login FTP :" . $ftp->message . "\n"; 
print L1 "Login to FTP was successfull\n"; 
$ftp->cwd("/") 
    or die print L1 "ftp_cd failed: " . $ftp->message . "\n"; 
foreach my $file_to_fetch ($ftp->ls($remotefile)) { 
    $ftp->get($file_to_fetch, $localfile) or die print L1 "Could not get file from FTP :" . $ftp->message . "\n"; 
    $remotefile = $file_to_fetch; 
    print "\$file_to_fetch ::: $file_to_fetch\n"; 
    print L1 "File - ${file_to_fetch} Successfully Downloaded from FTP\n"; 
    $ftp->rename($file_to_fetch, $archivefile) 
     or die print L1 "Could not move file to archive directory :" . $ftp->message . "\n"; 
    print L1 "File - ${file_to_fetch} Moved to archive directory as CAP_${file_date_time}.csv\n"; 
} 
$ftp->quit; 

print L1 "FTP process was successfully completed\n"; 
if (-s $localfile) { 
    open F1, "$localfile" 
     or die(print L1 "$localfile cannot be opened for reading \n"); 
} else { 
    die(print L1 "$localfile does not exist \n"); 
} 

在執行上面的代碼,如果我搜索文件FTP是不存在,但它不打印模具說法,這是「無法從FTP獲取文件」記錄,而不是它出來的FTP並繼續下一組打印的代碼L1「FTP過程已成功完成\ n」。

請幫助我解決這些問題,爲什麼die聲明不能在foreach中工作,如果它無法從FTP獲取文件。

回答

2

替換,

$ftp->get($file_to_fetch,$localfile) or die print L1 "Could not get file from FTP :" . $ftp->message ."\n"; 

$ftp->get($file_to_fetch,$localfile) or die "Could not get file from FTP :". $ftp->message ."\n"; 

如在第一種情況下dieprint()返回值作爲參數,而不是錯誤消息。

或者使自己的功能,

sub mydie { 
    my ($msg) = @_; 

    print L1 $msg; 
    die $msg; 
} 

,或者功能是不是一種選擇,

$ftp->get($file_to_fetch,$localfile) or do { 

    print(L1 $_), die($_) for "Could not get file from FTP :". $ftp->message ."\n"; 
}; 
+0

請留下評論時反對投票正確答案。 – 2014-10-06 17:38:50

+0

這個答案沒有解決爲什麼代碼不會死,這是個問題。 – darch 2014-10-13 16:50:32

+0

@darch OP想要用相同的信息打印和死亡,並且程序打印他想要的東西,但是死於'1'消息。上面的答案解釋了爲什麼沒有期望的行爲,以及如何實現它。所以代碼明確死亡(https://eval.in/205481),但不是在OP想要的方式。 – 2014-10-13 17:57:57

0

您的問題棱因爲你從print聲明傳遞的返回值來die

... or die print L1 "Could not get file from FTP :" . $ftp->message . "\n"; 

我懷疑你是e試圖將die語句的輸出鏡像到文件和STDERR。

如果是這樣的話,那麼我建議你做到以下幾點:

  1. 更改所有die print L1語句只是die

  2. 從每個die消息爲的刪除尾隨換行符\n隱藏行號信息。

    $ftp->login($ftpUser, $ftpPW) 
        or die "Could not login FTP :" . $ftp->message; 
    
  3. 創建$SIG{__DIE__}處理程序,以反映您die輸出到文件句柄。

    local $SIG{__DIE__} = sub { 
        print L1 @_; 
        die @_; 
    }; 
    
+0

是的,半小時前。無論如何,我都會考慮向OP和潛在其他人提供援助的信息,所以我們會忽略它。 – Miller 2014-10-13 18:22:59