giordano
giordano

Reputation: 3152

Perl: Does file and directory testing not work with Net::FTP

I would like to test files and directories which I downloaded with ftp if they are files or directories. With the code below I always get the else statement (2,4,6) what ever $x is (file or directory). What is wrong with this code?

use Net::FTP;

my $host = "whatever";
my $user = "whatever";
my $password = "whatever";

my $f = Net::FTP->new($host) or die "Can't open $host\n";
$f->login($user, $password) or die "Can't log $user in\n";

# grep all folder of top level
my @content = $f->ls;

# remove . and ..
@content = grep ! /^\.+$/, @content;

foreach my $x (@content) {

    print "\n$x: ";
    if ( -f $x ) {print " ----> (1)";} else {print " ----> (2)";}
    if ( -d $x ) {print " ----> (3)";} else {print " ----> (4)";}
    if ( -e $x ) {print " ----> (5)";} else {print " ----> (6)";}
}

Upvotes: 0

Views: 248

Answers (1)

stevieb
stevieb

Reputation: 9296

Per my comments in the OP, ls simply returns a list of names of the entities, it does not fetch them to the local machine. To get files along with directories, you'll need to use Net::FTP::Recursive. Here's an example:

use warnings;
use strict;

use Net::FTP::Recursive;

my $host = 'localhost';
my $user = 'xx';
my $password = 'xx';

my $f = Net::FTP::Recursive->new($host) or die "Can't open $host\n";
$f->login($user, $password) or die "Can't log $user in\n";

my @content = $f->ls;

@content = grep ! /^\.+$/, @content;

# note the rget() below, not just get. It's recursive

$f->rget($_) for @content;

foreach my $x (@content) {

    print "\n$x: ";
    if ( -f $x ) {print " ----> (1)";} else {print " ----> (2)";}
    if ( -d $x ) {print " ----> (3)";} else {print " ----> (4)";}
    if ( -e $x ) {print " ----> (5)";} else {print " ----> (6)";}
}

Example output:

a.txt:  ----> (1) ----> (4) ----> (5)
dir_a:  ----> (2) ----> (3) ----> (5)

Upvotes: 4

Related Questions