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

I have two drives: C and D

I have a file, namely  c:\dir1\dir2\dir3\myfile.txt
What are the various ways in perl, thru which I can copy myfile.txt from C drive to a folder in D drive, say D:\test\, so that I can replicate the entire directory structure, and the result would look like  D:\test\dir1\dir2\dir3\myfile.txt?

Replies are listed 'Best First'.
Re: Directory Creation Routine
by ysth (Canon) on Nov 24, 2004 at 12:22 UTC
    To create multiple directories at once, use File::Path's mkpath. Note that it dies on error, so wrap it in an eval {} and check $@ if you need to continue on error. Untested:
    use File::Path "mkpath"; use File::Copy; eval { mkpath(['d:\test\dir1\dir2\dir3']); 1 } or warn "couldn't create path: $@"; copy('c:\dir1\dir2\dir3\myfile.txt', 'd:\test\dir1\dir2\dir3\myfile.txt');
    If you just are given the 'c:\dir1\dir2\dir3\myfile.txt' and 'd:\test' names and need to split off and reassemble the directory name, look at File::Spec.
Recusively copy directories.
by exussum0 (Vicar) on Nov 24, 2004 at 12:16 UTC
    1. Check File::Copy to do the copying of a single file.
    2. Write a recursive function that, if it bumps into a file, copy it, if it's a directory, create the new dest directory and copy stuff into it.

    something ala.. (untested! gotta go to work!)

    Update: Woops.. thought you wnated to copy directories, not single files. Morning eyes.
    Update 2: Retitled to something more appropos..

    use File::Copy; sub rCopy { my $src = shift; my $dest = shift; if( -f $src ) { copy $src, $dest; } else if( -d $src ) { mkdir $src . "/" . $dest; my $dh = undef; opendir( $dh, $src ); while( my $rSrc = <$dh> ) { rCopy $rSrc, $src . "/" . $dest; } } }

    ----
    Then B.I. said, "Hov' remind yourself nobody built like you, you designed yourself"