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

I wrote a simple script to copy the files if I hard code each source and destination, but I want to get the script to look at each subdir and copy the files in each to a corresponding destination subdir. I need it to look at all subdirs in a directory structure and perform the copy at each level. Thanks, David
  • Comment on How do I copy files in a dir and continue into each subdir?

Replies are listed 'Best First'.
Re: How do I copy files in a dir and continue into each subdir?
by pjf (Curate) on Oct 03, 2001 at 15:07 UTC
    File::Find is almost certainly what you're after, although the man page is a bit much to digest if you've never seen it before.

    The big power of File::Find lays in the "wanted" function that you pass it. This can do pretty much anything you want. If (for example) you wanted to take each file you find and print it in rot13 to stdout, you could do something like this:

    #!/usr/bin/perl -w use strict; use File::Find; # The shift here takes the first command line # argument and uses that as our path. find(\&rot_cat,shift); sub rot_cat { unless (open(INFILE,$_)) { warn "Can't open $_ - $!\n"; return; } local $/ = undef; # Slurp mode. my $contents = <INFILE>; # Rot13 our contents. $contents =~ tr/A-Za-z/N-ZA-Mn-za-m/; # Print our new file. print $contents; }
    If you're copying files, your task is a little more tricky, as you'll need to create directories along the way, and make sure you know where in the source tree you are, and ensure you copy files to the appropriate plate in the destination tree.

    Personally, if you're just copying trees of files around, I'd suggest you look at good ol' "cp -r" if you're on a UNIX flavoured system. It's much more understandable and obvious, and does its job extremely well. Indeed, doing a "cp -r" and then using File::Find will usually be a simplier problem to solve.

    Cheers,
    Paul

Re: How do I copy files in a dir and continue into each subdir?
by davorg (Chancellor) on Oct 03, 2001 at 14:27 UTC

    You should look at the File::Find module.