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

Im writing a program that has to open up all the files in a directory and perform a test on their content. I need a function that will first give me an array with all the files in said directory. I don't want to perform the function on the files while I get all the filenames, I just want a function that will throw the filenames in an array so I can do stuff with them later.

I tried this but it doesn't seem to work:

@numfiles = grep { /^\.txt/ && -f "$directory/$_" } readdir(DIR);

All the files are .txt files.

Replies are listed 'Best First'.
Re: seeing all files in a directory
by Hot Pastrami (Monk) on Dec 22, 2000 at 02:21 UTC
    Also note that you must opendir() before readdir() will work.

    Here's one alternative to readdir()... it assumes that $path is set appropriately, and you want all ".txt" files:
    my @numfiles = glob("$path/*.txt");

    Hot Pastrami
Re: seeing all files in a directory
by ryddler (Monk) on Dec 22, 2000 at 09:08 UTC

    Here's an even shorter way to grab all .txt files from the current directory:

      @files = <*.txt>;

    Note that you can still put path info in front of the expression like this:

      @files = <./*.txt>;

    or this:

      @files = <../../*.txt>;

    but the filenames stored in your array will contain the "./" or "../../"

    ryddler

      It doesn't get much simpler than that.
Re: seeing all files in a directory
by Fastolfe (Vicar) on Dec 22, 2000 at 01:24 UTC
    The regular expression /^\.txt/ will match only filenames that start with ".txt", which doesn't seem to be what you want. This match fails for each file, giving you an empty list. Perhaps you want /\.txt$/?
Re: seeing all files in a directory
by lemming (Priest) on Dec 22, 2000 at 01:24 UTC
    Your grep will only match files that begin with .txt, try /\.txt$/ which will match files that end with .txt