Search code examples
perlwildcardfile-copying

How to recursively copy with wildcards in perl?


I've modified some script that I've written to now only copy .jpg files.

The script seems to work. It will copy all of the .jpg files from one folder to another but the script is meant to continually loop every X amount of seconds.

If I add a new .jpg file to the folder I'm moving items from after I have already started the script it will not copy over the newly added file. If I stop and restart the script then it will copy the new .jpg file that was added but I want the script to copy items as they are put into the folders and not have to stop and restart the script.

Before I added the glob function trying to only copy .jpg files the script would copy anything in the folder even if it was moved into the folder while the script was still running.

Why is this happening? Any help would be awesome.

Here is my code:

use File::Copy;
use File::Find;
my @source = glob ("C:/sorce/*.jpg");
my $target   = q{C:/target};

while (1)
{ sleep (10);
find(
   sub {
     if (-f) {
        print "$File::Find::name -> $target";
        copy($File::Find::name, $target)
         or die(q{copy failed:} . $!);

    }
    },
@source
); 

}

Solution

  • Your @source array contains a list of file names. It should contain a list of folders to start your search in. So simply change it to:

    my $source = "C:/source";
    

    I changed it to a scalar, because it only holds one value. If you want to add more directories at a later point, an array can be used instead. Also, of course, why mix a glob and File::Find? It makes little sense, as File::Find is recursive.

    The file checking is then done in the wanted subroutine:

    if (-f && /\.jpg$/i)