Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

I am using the rename($oldfilename,$newfilename) to move files around, but I want it to create directories as necessary, which it is not doing. How can I do this? Thanks.

Replies are listed 'Best First'.
Re: rename and create directories
by duff (Parson) on Nov 30, 2004 at 21:13 UTC

    You'll have to create the directories separately from the rename() because rename() doesn't do that. Read perldoc File::Path. Look for the mkpath routine.

      Note that in addition, rename doesn't (typically) span filesystems; so you end up needing File::Copy::move or equivalent, too.
      Thanks guys, I had suspected that rename didn't support that but didn't know what alternative to seek. Now I'm stuck tryiing to make a regex that will chop the filename off of a directory string like c:\bla\did\dy\blah.txt to be c:\bla\did\dy. Can you answer this one as fast?

      Currently I am splitting the string on "\" and reconstructing it without the last array element. Surely there is a better way.
        Currently I am splitting the string on "\" and reconstructing it without the last array element. Surely there is a better way.

        Indeed there is, use File::Basename, and thy foot shall step upon the path of goodly ways.

        ### ... sample snippet ... my ($basename,$path,$extension) = File::Basename::fileparse($fullpath,qw(.txt));

Re: rename and create directories
by gaal (Parson) on Nov 30, 2004 at 21:12 UTC
    Try File::Copy. The move function will do what you want.

    Update: Hmmm, actually, if it doesn't do the "create directories" bit -- the destination doesn't exist at all -- then you may need to also muck about with File::Path::mkpath.

Re: rename and create directories
by prasadbabu (Prior) on Dec 01, 2004 at 01:26 UTC

    You can make use of the File::Basename as scooterm suggested.

    $path = c:\bla\did\dy\blah.txt ; $filename = basename($path); $dirname = dirname($path); print "filename:$filename\ndirecory:$dirname";

    output:

    filename:blah.txt directory:c:\bla\did\dy

    cheers

    Prasad

Re: rename and create directories
by TedPride (Priest) on Nov 30, 2004 at 22:55 UTC
    my ($folder, $file) = $path =~ /(.*\\)(.*)$/;

      ... but note that this method does not work if your path is specified using forward-slash ("/") as the pathstep delimiter.