in reply to How can I compare two directories and copy over files missing from one to another?

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

  • Comment on Re: How can I compare two directories and copy over files missing from one to another?
  • Select or Download Code

Replies are listed 'Best First'.
Re^2: How can I compare two directories and copy over files missing from one to another?
by habhab (Acolyte) on Sep 17, 2004 at 20:58 UTC
    Thanks for your replies, guys. Whats good is that I actually understand what's going on.