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

Novice here. I am using an ftp script to get some files from a Unix server. How do I test to see if an item listing is a directory or a file? Here is a snippet of my code where I would need to test the item(given that I have already established a connection to the server and navigated to the correct directory).
@files = $ftp->ls; foreach $file1 (@files) { if($file1 !~ a directory){skip it}; if($file1 !~ a file) { $ftp->get($file1) || die "Can't get files from $dir :@{[ $ftp->m +essage ]}\n"; } } $ftp->close(); }

Replies are listed 'Best First'.
Re: Testing Files and Directories
by saintmike (Vicar) on Apr 26, 2004 at 17:18 UTC
    There's a module on CPAN to help you with this, File::Listing:
    foreach my $entry (File::Listing::parse_dir($ftp->dir())) { my($name, $type, $size, $mtime, $mode) = @$entry; next if $type eq 'f'; # plain file # ... do something with directories ... }
Re: Testing Files and Directories
by CountZero (Bishop) on Apr 26, 2004 at 21:47 UTC
    Net::FTP::Common seems a good bet.

    You can get the full dir-listing and if you check the 'perm' key in the hash of each entry, you will see that the first character is either a 'd' for a directory or a '-' for a file.

    use Data::Dumper; use Net::FTP::Common; $common_cfg = { Host => 'your.ftp.server', User => 'anonymous', Pass => 'me@here.there', RemoteDir => '/' } ; $ftp = Net::FTP::Common->new($common_cfg, Debug => 0); @dir = $ftp->dir(); print Dumper(\@dir); $ftp->quit;
    Warning: Tested on a Windows XP Home Edition system. YMMV on Unix

    CountZero

    "If you have four groups working on a compiler, you'll get a 4-pass compiler." - Conway's Law

Re: Testing Files and Directories
by fluxion (Monk) on Apr 26, 2004 at 19:06 UTC
    -e will test true if the file exists, and it'll also return false if the target exists, but isnt a file (directory). The same holds true for -d with respect to directories. Using these, your code would be written as follows:
    @files = $ftp->ls; foreach $file1 (@files) { next if(-e $file1); # skip non-directories if(-d $file1) { $ftp->get($file1) || die "Can't get files from $dir :@{[ $ftp->message ]}\n"; } } $ftp->close();

    Roses are red, violets are blue. All my base, are belong to you.

        whoops. yah, looks like the best method would be to parse the output of ls -l, as suggested by the first reply.

        Roses are red, violets are blue. All my base, are belong to you.

Re: Testing Files and Directories
by wolfi (Scribe) on Apr 27, 2004 at 06:36 UTC
    ignore post, please
    was going to suggest checking for periods in the files - but realized this wouldn't work