Is there a command to open a file as well as to create the directoryif it is not exist?

P

Peng Yu

Hi,

The following code would give the following error, if the dir 'xy'
does not exist.

print() on closed filehandle OUT at ./open.pl line 7.

I'm wondering if there is a perl command that is smart enough to
create an directory automatically when it opens a file for write.

Thanks,
Peng


#!/usr/bin/perl

use strict;
use warnings;

open(OUT, '>xy/abx.txt');
print OUT "Hello World\n";
 
J

Jürgen Exner

Peng Yu said:
I'm wondering if there is a perl command that is smart enough to
create an directory automatically when it opens a file for write.

I wouldn't want to use such a command, the chances of messing up the
file system are just too big.

Why not simply check if the directory exists (-d) and if it doesn't then
create it (after confirming, that you really, really meant to create a
new directory).
If it's a tree then use File::path to create the whole tree with one
call.

jue
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,969
Messages
2,570,161
Members
46,708
Latest member
SherleneF1

Latest Threads

Top