First off, uncomment use strict;! Then add the my to declare each variable. Note though that you need to declare @Filenames outside the loop.

Note that #recursively search  $path for files is a lie. There is no recursion and the search will only find files in the top level directory. If you want to actually perform a recursive search you need to do a little more work. At that point File::Find is likely what you want. Taking that route, something like the following (untested) code is what you want:

#!/usr/local/bin/perl -W # force taint checks, and print warnings use strict; # install all three strictures use File::Copy; use File::Find; my $path = "sourceDirectory"; #define full path to source folder my $newpath = "destinationDirectory"; #define path to new folder my @Filenames; $|++; # force auto flush of output buffer find (\&doCopy, $path); #Recursively search $path for files to copy sub doCopy { return if ! -f $File::Find::name; chdir($path) || die "cannot move to $path"; my $destFile = $newpath . $_; print "\$destFile = $destFile\n"; copy( "$_" , "$destFile" ) or print "File $_ cannot be copied. $!\ +n"; }

Note that you will probably have to clean up issues regarding paths to destination sub-directories in copy. You will probably need to do some magic with $File::Find::dir to strip off the root path and append the remaining path to $newpath.


DWIM is Perl's answer to Gödel

In reply to Re: Copying files between directories. How can I improve this code. by GrandFather
in thread Copying files between directories. How can I improve this code. by richill

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.