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

What is the best way to move a directory from one place to another?

Something more Perl than
qx(mv /home/my/this_dir /usr/local/elsewhere/);

  • Comment on What is the best way to move a directory?

Replies are listed 'Best First'.
Re: What is the best way to move a directory?
by jbert (Priest) on Nov 28, 2006 at 17:49 UTC
    It's the same as for files. The underlying system call on unix is rename, and you will probably have success with calling the perl function of the same name. perldoc -f rename

    If you look at perldoc perlport and search for rename, you'll see that it works on Win32 too, but can't move between different logical volumes. I guess that means drive letters, but I don't really know. I would have thought the same limitation applied to Unix, to be honest.

      The rename system call (upon which the Perl rename is built) cannot rename files across different devices (i.e. across mount points, say from /home/foo/bar to /nfsmount/baz). See File::Copy and its move routine.

        Thanks! The fact that File::Copy is one of the standard (already installed) Perl modules is a plus.

        ---------------------------- use File::Copy; my $source_dir = '/home/my/this_dir'; my $destination_dir = '/usr/local/elsewhere/this_dir'; move("$source_dir", "$destination_dir"); ----------------------------

        And I think this

        ----------------------------
        use File::Copy;
        use Carp qw(croak);
        
        move_reliable("$source_dir", "$destination_dir");
        
        sub move_reliable {
            my ( $source, $destination ) = @_;
            my $source_size = (-s $source) || 0;
        
            move( $source, $destination )
                || croak("move_reliable($source, $destination) failed: $!");
            my $destination_size = (-s $destination) || 0;
            croak(
                "move_reliable($source, $destination) failed copied $destination_size bytes out of $source_size"
                )
                if ( $source_size != $destination_size );
            1;
        }
        ----------------------------
        

        from Leon Brocard's File::Copy::Reliable is also nice.