in reply to New to Perl: Finding files on FTP

You don't even need to change the directory. Give this a shot -- it stores the contents of a directory and removes non-files

my $dir = '/genomes/Bacteria'; # use single quotes where possible, e.g., no var or \n # it's a tiny bit faster ## get the contents of a directory my @dir_listing = <$dir/*>; ## note: using <$dir/*/> would find all the directories ## removes . and .. while ($dir_listing[0] =~ /^\.+$/) { shift @{$dir_listing}; } ## removes all directories my @files_found = map { (-d $_) ? () : $_ } @dir_listing;

Replies are listed 'Best First'.
Re^2: New to Perl: Finding files on FTP
by Klaas (Initiate) on Mar 14, 2012 at 18:03 UTC

    Thanks! You are right, I don't need to change the directory. Let me experiment with your code a bit, need to understand the map function and get a better grasp of the

    while ($dir_listing[0] =~ /^\.+$/) { shift @{$dir_listing}; }
    I guess I would do this with a for loop, so I can just shift $dir_listing at position i. And I need to search all the subdirs as well, but I think I'll find a way. Thanks again!
      If you can't change to the directory, you probably can't list the directory or get files from the directory either. Add $ftp->message() to all the "or die" messages after the connect to get the reason for failure (on connect, $@ gives the reason). E.g.:
      ... or die "cannot list any DIRs " . $ftp->message();
        Thanks, will do!

      So...I made a mistake. I generally prefer to use array and reference hashes, so shift @{$dir_listing} was out of habit. However, the code I gave actually declared an array so, shift @dir_listing;is the correct way to do it.

      Regarding your comments, the while loop looks at the first element in the array and checks to see if it is just a series of dots using a regex, i.e., either '.' or '..'. If so, it removes the first element and checks again.

      For map, you can think of it as a very specialized foreach loop (map { <expr> } <array>) that returns values depending on the code used in the brackets. However, it is a little slower than a foreach loop so you generally only want to use it when you're using its output. It's a great way to modify or filter out values from an array.