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

Hi Monks, I am looking for the following functionality. A perl script that connects to an FTP server, - downloads files (which match a certain name) into a local folder. - deletes the files on successful download. So far i am upto this point where i can print out the matched files. I can't seem to download them or delete them.
use Net::FTP; use File::Copy; $Login = "abc"; $Pwd = "pwd"; $ftpHost = "10.23.2"; $ftpFolder = "F1"; $matchPattern = "Jeeves"; $LocalDirectory = \etc\local; $ftp=NET::FTP->new($ftpHost,Timeout=>100); $ftp->login($Login,$Pwd); $ftp->cwd($ftpFolder); # to find files that match the pattern @files = grep /$matchPattern/, $ftp->dir foreach(@files) { print $_; # Successfully prints the filename, but with all the details like perm +issions date created etc. # I need to write a code that helps me get this file out into a local +directory # I need to then delete the file. }
Can you please help.

Replies are listed 'Best First'.
Re: FTP - Download Multiple Files Matching Pattern
by tokpela (Chaplain) on Aug 17, 2009 at 11:07 UTC

    You need to download using a fullpath. Add the FTP directory to the filename before you can download it.

    foreach(@files) { my $filename = $_; my $fullpath = "$ftpFolder/$filename"; # download the file if ($ftp->get($fullpath)) { # be sure to only delete the file if it successfully downloaded # then delete the file. if ($ftp->unlink($fullpath)) { print "DELETED FILE: [$filename]\n"; } else { print "[Error] UNABLE TO DELETE THE FILE: [$filename][" . $ftp->m +essage . "]\n"; } } else { # error - not able to download print "[Error] UNABLE TO DOWNLOAD FILE: [$filename][" . $ftp->messa +ge . "]\n"; }

Re: FTP - Download Multiple Files Matching Pattern
by Bloodnok (Vicar) on Aug 17, 2009 at 11:05 UTC
    I'm only guessing (having never used NET::FTP in anger), but the docs suggests that using the ls() method on the NET::FTP object (c/w dir()) would yield the required list...

    Also, note that grep can be used in the foreach loop to the same effect i.e. foreach (grep ....

    A user level that continues to overstate my experience :-))
Re: FTP - Download Multiple Files Matching Pattern
by dwm042 (Priest) on Aug 17, 2009 at 19:16 UTC
    With all due respect to tokpela, whose reply is otherwise good, absolute paths in the context of FTP may or may not work. It's highly server dependent, how these things are interpreted. You can see this article for more details. It is useful to download a file or two manually to optimize the specifics of any automated transmission.

Re: FTP - Download Multiple Files Matching Pattern
by belg4mit (Prior) on Aug 19, 2009 at 03:40 UTC