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

I am using opendir() and readdir() to grab the contents of the current directory. My question is what would be the best way to determine if each object in this directory is a file or a sub directory?

I ask because I want to perform further functions (like opening and reading in contents) of only the non-directory files in this current directory.

  • Comment on Determine if object is file or directory?

Replies are listed 'Best First'.
Re: Determine if object is file or directory?
by halley (Prior) on Apr 07, 2004 at 18:33 UTC
    print "nothing\n" if not -e $filename; print "directory\n" if -d $filename; print "file\n" if -f $filename;
    perlfunc - see the -X pseudo-functions.

    --
    [ e d @ h a l l e y . c c ]

      Remember to prepend the directory to the filename:
      opendir D, "pbed" or die; while (my $file = readdir D) { if (-d "pbed/$file") { print "dir: $file\n"; } else { print "file: $file\n"; } }
        Or skip the ugly readdir() dance altogether. It's amazing how many people like going around their elbow to get to their thumb. Use glob() or the angle brackets, that's why they are there.
        @files = grep { not -d } <$path/*>;

        --
        [ e d @ h a l l e y . c c ]

Re: Determine if object is file or directory?
by jdporter (Paladin) on Apr 07, 2004 at 18:34 UTC
    The -f and -d operators do exactly this. See the perl docs for built-in functions and look at the description of -X.

    jdporter
    The 6th Rule of Perl Club is -- There is no Rule #6.

      Or rather than trudging through perlfunc jump straight to it with perldoc -f -X.

        What, didn't you like my -X link?

        jdporter
        The 6th Rule of Perl Club is -- There is no Rule #6.