2011-10-24 53 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