http://www.perlmonks.org?node_id=1011255

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

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 (Canon) 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.

A reply falls below the community's threshold of quality. You may see it by logging in.