SPUG: getting a list of directories

Ken McGlothlen mcglk at serv.net
Thu Jan 20 15:36:03 CST 2000


Mark Mertel <mmertel at ix.netcom.com> writes:

| On Thu, 20 Jan 2000, Todd Wells wrote:
| > I'd like to get a list of directory names (and only directory names) in
| > /usr/myapp.  What's the best way to go about this?  I wish the cookbook had
| > a recipe for this.  I see that readdir specifically excludes directory
| > names.
| 
| @files=<*>;
| for $file (@files) {
| 	print $file."\n" if -d $file;
| }

Globbing is rarely a great idea, though.  A more robust way to do this would be
something like (and I'll write it as a function):

	sub directories_in {
	    my( $directory ) = shift;
	    my( @result ) = ();
	    opendir( D, $directory );
	    while( $_ = readdir( D ) ) {
		push( @result, $_ )  if( -d $_ );
	    }
	    closedir( D );
	    return( @result );
	}

Just call that with something like

	@list = &directories_in( "/usr/myapp" );

I haven't tested it, but it's pretty straightforward.

 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    POST TO: spug-list at pm.org        PROBLEMS: owner-spug-list at pm.org
 Seattle Perl Users Group (SPUG) Home Page: http://www.halcyon.com/spug/
 SUBSCRIBE/UNSUBSCRIBE: Replace ACTION below by subscribe or unsubscribe
        Email to majordomo at pm.org: ACTION spug-list your_address





More information about the spug-list mailing list