Beefy Boxes and Bandwidth Generously Provided by pair Networks
good chemistry is complicated,
and a little bit messy -LW
 
PerlMonks  

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\file.pl I am creating the file.pl and directory temp does not exist. Is there any way to create the temp directory while creating file.pl itself or I have to creat directory first and then create file ?

Comment on create directories while creating a file
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 (Bishop) 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?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://1011255]
Approved by toolic
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others contemplating the Monastery: (4)
As of 2015-07-06 01:05 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The top three priorities of my open tasks are (in descending order of likelihood to be worked on) ...









    Results (68 votes), past polls