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

Ok...

I know TMTOWTDI, but what would be considered the more perlish way to copy a whole directory of files?

# This is not portable, right? system('cp', 'source_dir/*', 'dest_dir/'); # Is there was to do this without a loop/map? use File::Copy; opendir(INDIR, 'source_dir'); for my $file (readdir(<INDIR>)) { copy("source_dir/$file", "dest_dir/$file"); } # And of course there is always... (ick..) `cp source_dir/* dest_dir/*`;
Thanks in advance, Sifmole

Replies are listed 'Best First'.
Re: Perlish way of copying files
by stefan k (Curate) on May 03, 2001 at 18:29 UTC
    I'd take the use File::Copy path but to make sure that recursive copying is available make that a sub that might call itself (or at least check for directories and skip them). And don't forget to closedir INDIR; ;-)

    You might want to take a look at File::Path though that handles the creation of directories and not of files (AFAIK)

    Regards Stefan K

      Thanks for the point on the subdirs. I don't want it to recurse them, so I will just be making sure I toss them out.
(tye)Re: Perlish way of copying files
by tye (Sage) on May 03, 2001 at 18:59 UTC

    FYI, your first and last options won't work and it seems obvious to me that they aren't very "perlish". (:

    You could make your first work several ways but I'll just show you this one: system('cp',<source/*>,'dest/.') and die For the last one you just need to change that last "*" to a ".".

            - tye (but my friends call me "Tye")
      Why the angle brackets tye? Pardon my ignorance, please.
        Sifmole asked:
        Why the angle brackets tye?

        As you've probably noticed, I'm not tye. I hope you won't be so thoroughly dissappointed as to disregard my comments ;)

        tye wrote the following:

        system('cp',<source/*>,'dest/.') and die

        The angle brackets are what are known as a "filename globbing operator". Want all text files from the current directory?

        my @test_files = <*.txt>;

        However, if you want to use this with variables, it's better to use the glob operator:

        my @files = glob( $foo );

        Cheers,
        Ovid

        Join the Perlmonks Setiathome Group or just click on the the link and check out our stats.