如何安全地在写入模式下创建新文件?

时间:2014-10-03 06:08:52

标签: perl

我应该在写入模式下打开一个新文件并将数据输入其中。 请建议我,如何以安全模式打开新文件?

使用以下代码我收到错误“文件不存在或无法读取:/root/usr/data.xml;

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

1 个答案:

答案 0 :(得分: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;