Beefy Boxes and Bandwidth Generously Provided by pair Networks
Welcome to the Monastery
 
PerlMonks  

How to determine whether a dir entry is a directory?

by Codmate (Novice)
on Aug 22, 2001 at 18:20 UTC ( [id://106956]=perlquestion: print w/replies, xml ) Need Help??

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

I'm using File::stat to get each entry's mode. It returns lots of numbers whose meanings are a mystery to me. Where can I find out more about this? I either need to know what these mode numbers mean, or need a better way of testing for files and directories.
opendir FOLDERS, $path or die "opendir $path - $!"; for ( grep /[a-z]/, readdir FOLDERS ) { my $st = stat( $path.$_ ); my $mode = $st->mode; print $mode; } closedir FOLDERS;

Replies are listed 'Best First'.
Re: How to determine whether a dir entry is a directory?
by ozone (Friar) on Aug 22, 2001 at 18:25 UTC
    you can simply use the -f and -d flags to determine if something is a file or a directory, like so:
    my $fileA = "./something"; my $fileB = "./something/else.txt"; if(-d $fileA and -f $fileB) { ... }
    This will check to see if $fileA refers to a directory and if $fileB refers to a file...
Re: How to determine whether a dir entry is a directory?
by jffry (Hermit) on Feb 14, 2006 at 17:05 UTC
    sub readin_dirs { my $dir = shift; my $DIR; # I use variable file handles so function can be reentrant opendir $DIR, $dir or die "opendir $dir - $!"; my @entries = readdir $DIR; # Get only directories from dir listing. my @subdirs = grep { -d "$dir/$_" } @entries; # Remove "hidden" directories (including . and ..) from that list: @subdirs = grep { !/^\./ } @subdirs; for my $subdir ( @subdirs ) { now_do_something("$dir/$subdir"); } closedir $DIR; }
Re: How to determine whether a dir entry is a directory?
by RAS230 (Acolyte) on Feb 21, 2008 at 01:46 UTC
    You can use -d, but you have to be sure you're testing the correct pathname. Note that readdir returns unqualified names relative to the directory they're in.
    my $dir = "/anydir"; opendir DIR, $dir or die "opendir $dir : $! \n"; for ( readdir DIR ) { my $dirent = "$dir/$_"; if ( -d $dirent ) { print "$dirent is a directory\n"; } } closedir DIR;
Re: How to determine whether a dir entry is a directory?
by I0 (Priest) on Aug 22, 2001 at 21:23 UTC
    Fcntl has defines some symbols which can help here:
    use Fcntl ':mode'; $mode & S_IFDIR; S_ISDIR($mode);

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://106956]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others romping around the Monastery: (5)
As of 2024-04-19 15:40 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found