http://www.perlmonks.org?node_id=991533

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

Hi,

I need to fetch certain files from the server which has multiple subdirectories. How do i do it with NET FTP in Perl.

Example : \home\code\test and home\code\prod I need to search for files under code (the file may be present in 'test' or 'prod') and get that file to local.

The code I used - my $dir = "/home/code"; $f->cwd($dir) or die "Can't cwd to $dir\n"; $, = "\n"; my $fileto_get = "sample.sh"; $f->get($fileto_get) or die "Can't get $fileto_get from $dir\n";

This searches only in the specified directory 'code'. The file is present in 'tes't directory but it is not returned unless i change the directory to "/home/code/test".

Please guide me on how to fetch files, by mentioning only the parent directory.

Replies are listed 'Best First'.
Re: Net :: FTP
by cheekuperl (Monk) on Sep 04, 2012 at 05:04 UTC
    To get the files using Net::FTP from remote host, you will have to traverse the remote directory tree yourself. Check the methods in Net::FTP that allow you to list files and directories on remote server, change to that directory and get the file you're looking for.
      Also, as it throws error if I serach in the wrong directory and the execution stops, I cannot try in all the listed directories
        as it throws error if I serach in the wrong directory and the execution stops, I cannot try in all the listed directories
        Shouldn't be the case. You can always cd to directory and check for return codes of FTP list file command. It will tell you whether file exists or not. It won't terminate your program or your FTP session.
        Bottomline, you'll have to cd to each directory and look for the file.
      But i do not know in which directory the file exists. Can you please help me in this case?
Re: Net :: FTP
by aitap (Curate) on Sep 04, 2012 at 18:53 UTC

    First, set up a list of directories.

    $f->cwd($dir) or die "Can't cwd to $dir\n";
    Next, instead of dieing in case of inability to CWD, switch to the next list element in a foreach loop.

    For example:

    my @directories = qw/code test/; foreach my $dir (@directories) { $f->cwd("/home/$dir") || next ... # your code to fetch the files }

    Sorry if my advice was wrong.