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

I searched the other SOPWs and was linked to the main thread here for READDIR and OPENDIR but I can't get the example to work. I want to slurp up every file in a directory (in reality I want to slurp only .jpgs but there's only one type of file in the directory anyway). The script is run from within the same directory as the one I want to read from, which is why my $dir = "."

No errors, it's just not printing anything out. Any idea why?

#!/usr/bin/perl use warnings; use strict; my $dir = "."; opendir(DIR, $dir) || die "can't opendir $dir: $!"; my @dots = grep { /^\./ } readdir(DIR); closedir DIR; print join("\n", @dots);

Replies are listed 'Best First'.
Re: reading all files in a dir
by jeffa (Bishop) on Aug 25, 2006 at 18:11 UTC
Re: reading all files in a dir
by friedo (Prior) on Aug 25, 2006 at 18:19 UTC
    my @dots = grep { /^\./ } readdir(DIR);

    That finds all the files beginning with a . in your directory. You forgot to invert the regex for your grep. What you probably want is:

    my @not_dots = grep { !/^\./ } readdir(DIR);

    Then @not_dots will contain all the non-dotfiles.

Re: reading all files in a dir
by jwkrahn (Abbot) on Aug 25, 2006 at 18:21 UTC
    my @dots = grep { /^\./ } readdir(DIR);
    Your regular expression says to match only file names that begin with a period, you probably want:
    my @dots = grep { -f } readdir(DIR);
    Which will match only "plain" files or:
    my @dots = grep { /\.jpg\z/i } readdir(DIR);
    Which will match only JPEG files.

Re: reading all files in a dir
by swampyankee (Parson) on Aug 25, 2006 at 18:27 UTC

    If you look at your grep statement, you're only selecting files that start with a "dot". Ok; this is well and good. Indeed, it works just as I would expect (I run it and get this:

    . ..

    with no new line on the last line of output)

    I'm thinking this is the opposite of what you want, which is probably the files which don't start with a period, in which case your grep statement would look like this:

    my @dots = grep { ! /^\./} readdir(DIR);
    which will take out files which start with a period instead of the files which don't. As an (possibly preferable) alternative, you could use this:
    my @dots = glob("*"); # adjust argument to glob as needed

    Most of the time, I tend to prefer glob, mostly because I'm lazy (it saves a lot of typing). The exception is when I've got to deal with Windows (which is most of the time), where I find that glob seems to get confused with filenames containing blanks (yeah, I could escape them).

    emc

    Only two things are infinite, the universe and human stupidity, and I'm not sure about the former.

    Albert Einstein