2014-10-03 67 views
1

我应该在写入模式下打开一个新文件并将数据写入它。 请让我建议,如何在安全模式下打开一个新文件?如何安全地在写模式下创建新文件?

与下面的代码我得到错误“文件不存在或无法读取:/root/usr/data.xml;

my $new_file = "/root/usr/data.xml"; 
my $dom = $parser->load_xml(...); 
dom->toFile($new_file); 
+0

如何我是否首先创建新文件并在写入模式下打开? – Giri 2014-10-03 06:21:39

回答

1

试试这个代码:

use strict; 
use warnings; 
use autodie; 

my $new_file = "/root/usr/data.xml"; 
unless(-e $new_file) { 
    #Create the file if it doesn't exist 
    open my $fc, ">", $new_file ; 
    close $fc; 
} 

# Work with the file 
open my $fh, "<", $new_file; 
while(my $line = <$fh>) { 
    #... 
} 
close $fh; 
相关问题