2010-05-20 38 views
4

也許我在用錯誤的關鍵字搜索,或者這是一個非常基本的問題,但我無法找到我的問題的答案。我無法將我的whois命令的結果寫入新的外部文件。如何使用Perl將輸出寫入新的外部文件?

我的代碼如下。它需要$readfilename(它是一個包含IP列表的文件名)和$writefilename(它是輸出的目標文件)。兩者都是用戶指定的。對於我的測試,$readfilename在三條獨立線路上包含三個IP地址,因此在用戶指定的輸出文件中應該有三個單獨的whois結果。

if ($readfilename) { 
    open (my $inputfile, "<", $readfilename) || die "\n Cannot open the specified file.  Please double check your file name and path.\n\n"; 
    open (my $outputfile, ">", $writefilename) || die "\n Could not create write file.\n\n"; 
    while (<$inputfile>) { 
     my $iplookupresult = `whois $_ > $writefilename`; 
     print $outputfile $iplookupresult; 
    } 
    close $outputfile; 
    close $inputfile; 
} 

我可以執行該腳本,並用一個新的外部文件中結束,但在該文件的半部具有二進制垃圾數據(在CentOS運行),並且僅在WHOIS查詢中的一個(或一個的一部分)是可讀的。

我不知道我一半的文件是如何結束了二進制...但我的方法一定是不正確的。有沒有更好的方法來達到相同的結果?

+0

對不起,在我的一個測試的例子中有一個錯誤的變量。它已被刪除。 – Structure 2010-05-20 03:47:09

+0

我添加了「錯誤」腳本,以便其他人可以看到*不*做出愚蠢的錯誤。我花了很長一段時間試圖調試這... – Structure 2010-05-20 03:56:12

回答

7

您使用shell重定向重定向的whois輸出到文件中。但是你也打開了文件進行寫入,並試圖將數據寫入同一個文件,給你垃圾。只需放下外殼重定向:

print $outputfile `whois $_`; 
+0

你知道什麼好笑 - 那是我從我的例子中刪除的代碼,認爲它是錯誤的。我剛剛檢查過,它實際上還在我的腳本中,以及在我的測試過程中...... *嘆氣*謝謝! – Structure 2010-05-20 03:54:25

相關問題