Beefy Boxes and Bandwidth Generously Provided by pair Networks
Just another Perl shrine

create directories while creating a file

by rbala (Acolyte)
on Jan 02, 2013 at 12:13 UTC ( #1011255=perlquestion: print w/replies, xml ) Need Help??
rbala has asked for the wisdom of the Perl Monks concerning the following question:

Hi , I want to create a file inside a directory , the directory is to be dynamically created based on a variable. Suppose, if the file is to be C:\Users\temp\ I am creating the and directory temp does not exist. Is there any way to create the temp directory while creating itself or I have to creat directory first and then create file ?
  • Comment on create directories while creating a file

Replies are listed 'Best First'.
Re: create directories while creating a file
by toolic (Bishop) on Jan 02, 2013 at 12:20 UTC
    I don't think so, but you could create a function for yourself to emulate that behavior. File::Path::make_path can help.
Re: create directories while creating a file
by tobyink (Abbot) on Jan 02, 2013 at 12:51 UTC
    use Path::Class qw( file ); my $file = file '/tmp/foo/bar/baz.txt'; $file->dir->mkpath; print { $file->openw } "Hello world!\n";
    perl -E'sub Monkey::do{say$_,for@_,do{($monkey=[caller(0)]->[3])=~s{::}{ }and$monkey}}"Monkey say"->Monkey::do'
Re: create directories while creating a file
by ww (Archbishop) on Jan 02, 2013 at 13:00 UTC
    I think you'll find that you MUST first create the dir and then the file; it's an OS issue. In one manner or another, the dir holds pointers to its files.

    OTOH, as toolic suggested, you could create a dir and THEN create/store the file there and do both WITHIN a rather simple script. See perldoc -f mkdir for a function rather than a module.

    You're on your own re the file creation though; you've provided insufficient info.

Re: create directories while creating a file
by sundialsvc4 (Abbot) on Jan 02, 2013 at 21:36 UTC

    Seems to me that this is the “force directories” use-case ... and, while I can’t right now follow that idea all the way through, I am quite sure that CPAN provides a way to efficiently handle it .... i.e. “if these directories don’t exist yet, automagically create them and move along.”

      Thanks all for your cool ideas... File::Path qw(make_path) made it simple!

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://1011255]
Approved by toolic
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others lurking in the Monastery: (5)
As of 2018-02-21 18:05 GMT
Find Nodes?
    Voting Booth?
    When it is dark outside I am happiest to see ...

    Results (285 votes). Check out past polls.