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

Dear monks, Is it possible to read a dir and differentiate files and directories? please advice. thanks

Replies are listed 'Best First'.
Re: List and identify directories
by Happy-the-monk (Canon) on Jun 28, 2004 at 09:34 UTC

    ...read a dir and differentiate files and directories?

    perldoc -f readdir   to read directories.
    perldoc -f -X   for how to test if it's a file or a directory

    Update: added link for -X

    Cheers, Sören

      #!d:/perl/bin/perl.exe $dir =shift || '.'; opendir Dir, $dir or die "dir not found \$! \n"; @files = readdir(Dir); while(<@files>) { print "$_ \n" if -d _; }

      Edited by Chady -- code tags.

Re: List and identify directories
by tachyon (Chancellor) on Jun 28, 2004 at 10:09 UTC

    Here is a bit of line noise for you to ponder. It will print out all the files/dirs in a given directory and flag them.....

    print map{ -d $_ ? "DIR $_\n" : "FILE $_\n" } glob( "/some/dir/*" );

    cheers

    tachyon

      Is the -d method faster or more efficient than the opendir() method? Are there any advantages to either method. I currently use the opendir() in some apps. I really like what tachyon posted, but is it more or less efficient than my current solution?

        Any of the -X operators involve a call to stat(). You can use the cached result by doing if -f $_ and ! -l _ ie the '_' char accesses the (last) cached stat result. As for readdir vs glob I would expect them to be similar for speed. glob *is* different from readdir in one important way that can bite you if you don't expect it. With glob you will have the full/partial path you fed it in every result element. Sometimes this is very convenient as it saves adding the path, sometimes of course it is not. If it is convenient I use glob, if I just want the file/dir names without any path I use readdir.

        cheers

        tachyon