Giri
Giri

Reputation: 13

How to create a new file in write mode safely?

I should be open a new file in write mode and wite data into it. please let suggest me, how to open a new file in a safe mode ?

with below code i am getting error "file does not exist or cannot be read:/root/usr/data.xml;

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

Upvotes: 1

Views: 45

Answers (1)

Praveen
Praveen

Reputation: 902

Try this code :

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;

Upvotes: 1

Related Questions