2011-10-24 56 views
1

我希望得到一些幫助,以瞭解如何在perl中專門創建一個接收用戶輸入的文本文件。在perl中創建文本文件

print "\ndirectory has been changed"; 
print "\nDear user, please enter the name of the file you want to create "; 

my $nameFile = <>; 

open MYFILE, ">$nameFile" or die "couldn't open the file $!"; 

這將創建雖然不是一個文本文件的文件。

問候 阿里安

+0

您不應該對錯誤進行解釋(「我不認爲這是一個文本文件」),您應該準確地指出錯誤。例如。 「它有一個不規則的文件名」或「當我嘗試用vim打開文件時,它找不到它」 – TLP

回答

6

更新:我只是意識到你沒有chomp你STDIN那裏,所以你必須連接到你的文件名的最後一個換行符。

chomp $filename; 

應該用你的文件名解決特定的打嗝。

推薦使用open的方法是使用三個參數和一個詞法文件句柄。 MYFILE是一個全球性的,具有所有固有的缺點和好處。

use autodie; # will check important errors for you, such as open 
open my $fh,  '>',    $namefile; 
# ^- lexical ^- explicit mode ^- filename separated from mode 

print $fh "This is a textfile\n"; # put something in the file