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

Hi Monks
Am returning to some PERL after a little time away and am struggling a bit. I am having a problem filtering out directories, should this give me a list of anything that is not a windows folder/directory?
opendir DIR, "e:\\core\\ops_utilities\\" or die $!; my @files = grep {!-d $_} readdir(DIR);
Thanks for your guidance.

Replies are listed 'Best First'.
Re: -d on windows
by Corion (Patriarch) on Mar 27, 2008 at 12:53 UTC

    readdir returns a list of names, not of fully qualified paths. You can see that by printing out $_ and comparing that against "e:\\core\\ops_utilities\\$_". Only the latter will be what you expect.

    Whenever you find things from a grep not returning what you think, it helps to modify the grep to tell you what it does:

    my @files = grep { warn "Checking '$_' for -d:" . -d $_; !-d $_} readd +ir(DIR);
      Thanks for the reminder, it all came flooding back as soon as I read the first line.
      Code changed too
      my $dir = "e:\\core\\ops_utilities\\"; opendir DIR, $dir or die $!; my @files = grep {!-d $dir.$_} readdir(DIR);
      And all works as expected. Thank you
        Here's a variation that doesn't require an unusual trailing backslash, gives a better error message, and avoids using global variables:
        use File::Spec::Functions qw( catfile ); my $dir = "e:\\core\\ops_utilities"; opendir(my $dh, $dir) or die("Unable to read utilities directory \"$dir\": $!\n"); my @files = grep { !-d catfile($dir, $_) } readdir($dh);

        The following might be more useful:

        my @files = grep { !-d } map { catdir($dir, $_) } readdir($dh);
Re: -d on windows
by Pancho (Pilgrim) on Mar 27, 2008 at 12:51 UTC

    I tested this on windows and I get the files in the directory... What specific problem are you having?

    Pancho