in reply to Scanning a directory's files for readability

G'day Phoebus2000,

Welcome to the monastery.

"I am trying to process all text files in a directory"

[Note: this extends what ++Cristoforo posted.]

After "my @files = readdir(DH);", @files contains all filenames found in the directory being read. This will include all directories (at least the current ('.') and parent ('..') directories), symbolic links, named pipes and so on.

Try something along these lines (untested) to get what you want:

my $dir = './new_text'; opendir my $dh, $dir; my @files = grep { -f } map { "$dir/$_" } readdir $dh; closedir $dh;

'-f' is described, along with other file test operators, in -X.

Consider File::Spec for a more portable solution than "$dir/$_".

-- Ken

Replies are listed 'Best First'.
Re^2: Scanning a directory's files for readability
by Cristoforo (Curate) on Jan 20, 2014 at 00:50 UTC
    Found some funny results when testing the -f operator versus ! -d on my Windows 7 system.
    C:\Old_Data\perlp>perl -wE "opendir DIR, 'CSV';say for grep -f, readdi +r DIR" dat.txt DBD_CSV.pl my_db.txt my_db_2.txt o33.csv o33.txt o44.txt o55.csv text_csv.pl zip_codes.csv C:\Old_Data\perlp>perl -wE "opendir DIR, 'CSV';say for grep ! -d, read +dir DIR" csvfile.pl dat.txt DBD_CSV.pl dbd_csv_2tables.pl mytable my_db.txt my_db_2.txt name_cols_csv.pl o33.csv o33.txt o44.txt o55.csv placeholder.pl pmonk814937.pl selectall_hashref.pl test1.txt test_class_csv.pl text_csv.pl using_DBD_CSV.pl zip_codes.csv C:\Old_Data\perlp>
    -f doesn't get all the files that ! -d does.
      readdir returns dat.txt, because it finds CSV/dat.txt. -f, on the other hand, runs on dat.txt only, i.e. ./dat.txt. ! -d is true for files that exists in CSV, but do not exist in the current directory.
      لսႽ† ᥲᥒ⚪⟊Ⴙᘓᖇ Ꮅᘓᖇ⎱ Ⴙᥲ𝇋ƙᘓᖇ
        Thanks! grep with -f was finding files in the current directory (that were also in the CSV subdirectory). The correction would be to prepend the subdir to the filename to test with -f.

        grep -f qq[CSV/$_]

      I see that's been answered by ++choroba.

      The "map { "$dir/$_" }", in my suggested solution, provided "grep { -f }" with the pathname (as opposed to just a filename).

      I might also point out that while '! -d' will be true for the '-f' files, it may also be true for any '-l', '-S', '-b' or '-c' files.

      -- Ken