The logic in your sub wanted is flawed. Consider this scenario.

Source directory contains files: 'foo', 'baz, 'blurch'
Target directory contains files: 'foo', 'bar'

find (\&wanted, $Src); will take the first file, 'foo' and call wanted with $_ == 'foo'. wanted will compare 'foo' to 'foo' and print "File already in $Trg: $file\n". So far, so good. Then it will compare 'foo' to 'bar', and copy 'foo' to the target directory, where it already exists. And according to the docs for File::Find:

Trying to copy a file on top of itself is a fatal error.

Even if it survived that, if you follow the logic, it will be saying that the file is already there, when it wasn't, but it just happened to copy it in an earlier iteration of the for loop.

I haven't tested this, but I think you need to do this:

sub wanted { opendir (DIR, "$path/$Trg") or die "cannot opendir $Trg"; foreach my $file (readdir(DIR)) { if ($_ == $file) { print "File already in $Trg: $file\n"; return; } } copy("$_","$path/$Trg/$_"); closedir (DIR); }

which will first check all the files in target to see if the source file in question exists, and exit the sub if it does. Only if it survives that test will it be copied (and only copied once ;)

TheEnigma


In reply to Re: How can I compare two directories and copy over files missing from one to another? by TheEnigma
in thread How can I compare two directories and copy over files missing from one to another? by habhab

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.